Home >Web Front-end >JS Tutorial >How to set select in javascript
Method: 1. First obtain the select element; then use the val() method to select the select option with the specified value. 2. First get the element; then use the find() method to find the select option with the specified text value; finally use the "attr("selected",true)" method to select it.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
javascript settings select selected
For example
<select class="selector"></select>
1. Set the item with value to pxx selected
$(".selector").val("pxx");
2. Select the item with text set to pxx
$(".selector").find("option[text='pxx']").attr("selected",true);
There is a usage of brackets. The equal sign in the brackets is preceded by the attribute name. No need to add quotes. Many times, the use of square brackets can make logic very simple.
The colon is used here. Mastering its usage and drawing inferences will also make the code simpler.
Many times the cascade of selects is used, that is, the value of the second select changes with the value selected by the first select. This is very simple in jquery.
$(".selector1").change(function(){ // 先清空第二个 $(".selector2").empty(); // 实际的应用中,这里的option一般都是用循环生成多个了 var option = $("<option>").val(1).text("pxx"); $(".selector2").append(option); });
Recommended learning: javascript advanced tutorial
The above is the detailed content of How to set select in javascript. For more information, please follow other related articles on the PHP Chinese website!