Home >Web Front-end >JS Tutorial >Detailed example of how jquery allows select to select an option

Detailed example of how jquery allows select to select an option

黄舟
黄舟Original
2017-07-28 09:29:484550browse

Jquery How to let select select an option Detailed example

<span id="xx">广州市</span>
<select id="select_id">    
<option>北京市</option>    
<option>广州市</option>    
<option>上海市</option>
</select>

Let select select Guangzhou City?
Incorrect usage:

$("#select_id option[text=&#39;广州市&#39;]").attr("selected", true); 
<script>
//普通js写法
document.getElementById("select_id").options[1].setAttribute("selected", true);
//jquery应该这样写
$("#select_id option").eq(1).attr("selected",true);
</script>
<script>
   $("#select_id option[value=&#39;广州市&#39;]").attr("selected", true);
</script>
$("#select_id option[text=&#39;广州市&#39;]").attr("selected", "selected");


Correct usage:

 $("#select_id")[0].selectedIndex = 1;

How to set the select index in jquery and directly use the dom operation method to operate the index:

$(&#39;#selectId&#39;).get(0).selectedIndex=index;

Use value mode to operate index:

$(&#39;#selectId&#39;).val(&#39;selectIndexValue&#39;);


Extension:
Get the value of the currently selected item

$("#select_id").val();

Get the text of the currently selected item

$("#select_id").find("option:selected").text();

The above is the detailed content of Detailed example of how jquery allows select to select an option. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn