简体   繁体   English

如何通过jQuery选择选项

[英]How to make option select selected by jquery

Here is my HTML. 这是我的HTML。

<select class="height_selected" id="renderHeight">
    <option>Select Height</option>
    <option value="1">123 cm</option>
    <option value="2">125 cm</option>
</select>

I want to make the Option 2 ie, 125 cm as selected. 我要选择选项2,即125厘米。

I tried 我试过了

$('#1 :selected').text();

But it is not working. 但这是行不通的。

How can i make the option 125 selected ie, value that have #1 as selected 我如何才能选择选项125,即选择了#1

Update i have another option select 更新我还有另一个选择

I want to make only the height to be selected. 我只想选择高度。

<select class="weight_selected" id="renderWeight">
    <option>Select Weight</option>
    <option value="1">100 kg</option>
    <option value="2">125 kg</option>
</select>

Use prop to select the option . 使用prop选择option

$('#renderHeight option[value="2"]').prop('selected', true);

Code Demo 代码演示

 $('option[value="2"]').prop('selected', true); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <select class="height_selected" id="renderHeight"> <option>Select Height</option> <option value="1">123 cm</option> <option value="2">125 cm</option> </select> 

You can also set the value using val() . 您也可以使用val()设置值。

 $('#renderHeight').val(2); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <select class="height_selected" id="renderHeight"> <option>Select Height</option> <option value="1">123 cm</option> <option value="2">125 cm</option> </select> 

Try this : To make option selected, you can directly set value of select box to the value of option to be selected. 试试这个:要选择选项,您可以直接将选择框的值设置为要选择的选项的值。

 $(function(){ $('#renderWeight').val('2'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select class="weight_selected" id="renderWeight"> <option>Select Weight</option> <option value="1">100 kg</option> <option value="2">125 kg</option> </select> 

You can use val() by passing the option value 您可以通过传递选项值来使用val()

Live Demo 现场演示

$('#renderHeight').val(2);

You can try this code 您可以尝试此代码

 $('#renderHeight option').each(function(){ if($(this).text() =='123 cm'){ $(this).prop('selected',true) } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="height_selected" id="renderHeight"> <option>Select Height</option> <option value="1">123 cm</option> <option value="2">125 cm</option> </select> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM