简体   繁体   中英

Getting option element based on custom attributes

I have the following:

<select id="selector">
<option data-origin-table="foo1" data-origin-col="bar1">
<option data-origin-table="foo2" data-origin-col="bar2">
<option data-origin-table="foo3" data-origin-col="bar3">
...
</select>

I am trying to select an option based on the custom attributes but I am having no success.

I tried the following ways but they all failed.

console.log($('#selector option').filter(function () { return $(this)[0].getAttribute('data-origin-table') == "foo2" && $(this)[0].getAttribute('data-origin-col')=="bar2"; }).val());

console.log($('#selector option').filter(function () { return $(this).getAttribute('data-origin-table') == "foo2" && $(this).getAttribute('data-origin-col')=="bar2"; }).val());

console.log($('#selector option').filter(function () { return $(this).attr('data-origin-table') == "foo2" && $(this).attr('data-origin-col')=="bar2"; }).val());

Any clues on how to properly do this?

Using jquery 2.2.3 if it helps. Thanks!

To achieve this you can use an attribute selector:

 var val = $('#selector option[data-origin-table="foo2"][data-origin-col="bar2"]').val(); console.log(val); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="selector"> <option data-origin-table="foo1" data-origin-col="bar1" value="foo">A</option> <option data-origin-table="foo2" data-origin-col="bar2" value="bar">B</option> <option data-origin-table="foo3" data-origin-col="bar3" value="fizz">C</option> </select> 

Or you could use filter() :

 var val = $('#selector option').filter(function() { return $(this).data('origin-table') === 'foo2' && $(this).data('origin-col') === 'bar2'; }).val(); console.log(val); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="selector"> <option data-origin-table="foo1" data-origin-col="bar1" value="foo">A</option> <option data-origin-table="foo2" data-origin-col="bar2" value="bar">B</option> <option data-origin-table="foo3" data-origin-col="bar3" value="fizz">C</option> </select> 

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