<select id = "tester" class = "tester">
...
<option value = "code_2">2</option>
</select>
<select id = "tester" class = "tester">
...
<option value = "code_2">2</option>
</select>
If data
value is 2, I am trying to select every tester
whereby their option value contains 2
.
$('.tester').each(function() {
$(this option:contains(data)).prop("selected", true);
})
Selecting every tester
was successful but failed to change its option value. what could be the reason?
CodePudding user response:
HTML :
<select multiple>
<option value="">N/A</option>
<option value="code_2">2</option>
<option value="code_2">2</option>
<option value="code_2">2</option>
<option value="code_2">2</option>
</select>
<select multiple>
<option value="code_2">2</option>
<option value="code_2">2</option>
<option value="code_2">2</option>
<option value="code_2">2</option>
</select>
Javascript with Jquery
var data = 2;
$(document).ready(function(){
$('.tester').each(function() {
$(this).children().each(function(i, element) {
if($(element).text() == data){
$(element).prop("selected", true)
}
});
})
});
NB: Don't use the same ID twice on the same page. To show multiple options selected. Use multiple Attribute on select tag
CodePudding user response:
You can try this code if you want to use jQuery:
$('.tester').val('code_2').change();
Where:
.tester
- is select
selector
code_2
- is option
value
This code allows you to don't search option
by yourself
Check the documentation jQuery.val()