I've a lot of <option>
s in a <select>
and and extra attribute called zip
<SELECT id="city">
<OPTION zip="AUC 1291 100005" value="1">City 1</OPTION>
<OPTION zip=" 1295 100006" value="2">City 2</OPTION>
<OPTION zip=" 1299 100008" value="3">City 3</OPTION>
</SELECT>
Now I want to select the Option which Text or ZIP contains a string value, but the following code doens't work.
var val = '1291'; //Zip code
var x = $('#city option:contains('+val+'), #city zip:contains('+val+')').val();
Why?
If you want to select the elements with attribute, taht value contains requested string, you have to use:
var val = '1291'; //Zip code
var x = $('#city option[zip*="' + val + '"]').val();
As mentioned: http://api.jquery.com/attribute-contains-selector/
But as guys said, the better way is to have HTML5 data-zip
attribute instead of zip
(just prefix with data-
).
In this case, your selector will be:
var x = $('#city option[data-zip*="' + val + '"]').val();
Hope it helped.
contains
checks for inner elements not for attributes, you should go with something like:
$('#city option').filter(function(){
return this.innerHTML.indexOf(val) > -1 ||
$(this).attr('zip').indexOf(val) > -1;
});
Note that zip
is not a valid HTML attribute, it would be wise to use data-zip
instead.
$('#city option').filter(function(){
return this.innerHTML.indexOf(val) > -1 ||
$(this).data('zip').indexOf(val) > -1;
});
Here`s the answer to my questions. Tested and works :)
var x = $('#city option:contains('+val+'), #city [data-zip*='+val+']').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.