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
I have some selects
<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>
You can pass the desired option value to .val()
method while targeting select to select required option element:
$('select').val('2');
Working Snippet:
$('select').val('2');
<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>
You can explore the value
key of this jquery object
$('select').each(function() {
var selected = $(this)[0].value;
console.log(selected)
if (selected != 2) {
alert("Not 2")
}
})
JSFIDDLE