jQuery循环进行选择并设置选择的选项 [英] jQuery Loop through selects and set selected option
问题描述
我想遍历页面上的所有选择输入,如果选择的值不是某个选项,则将该值设置为选择"
I'd like to loop through all of the select inputs on a page and if the selected value is not a certain option then set that value to selected
我有一些选择
<select name="select1">
<option value="1">One</option>
<option value="2" selected>Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<select name="select2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<select name="select3">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
我正在像这样遍历它们,但是我不知道如何将所选属性设置为选项"2"(如果尚未选择)
I'm looping through them like so, but I can't figure out how to set the selected property to option '2' if it isn't already selected
$('select').each(function() {
var selected = $(this).find(":selected");
if (selected.val() != 2) {
// do some stuff
}
}
我应该详细说明.如果选择输入值发生更改,我会附加一个字符串,例如-更新"到输入值,因为每个输入都将发布到数据库中.理想情况下,我只会对因效率而更改的输入执行此操作
I should elaborate. If a select input value is changed, I'm appending a string e.g. '-updated' to the input value as each input will be posting off to a database. Ideally I'd only do this for inputs that have changed for efficiency
因此,我想将尚未选择选项2的所有选择输入设置为"2更新"
So I'd like to set all selects inputs that don't already have option 2 selected to be selected and have a value of "2-updated"
感谢到目前为止的所有答案
Thanks for all of the answers so far
推荐答案
查找值等于2的所有选项,然后选择它们:
Find all options with value equal to 2 and select them:
$('select').each(function() {
$(this).find('option[value="2"]').prop('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3" selected>Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<select name="select2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<select name="select3">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
这篇关于jQuery循环进行选择并设置选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!