简体   繁体   中英

Searching select option value using Jquery

<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?

HTML:

<select class="tester" 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  class="tester" 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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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