I'm trying to use jQuery to check for the existence of an <option>
that contains a particular string of text. My attempts so far are not working as I expect. Here's the HTML:
<select>
<option value="13">General</option>
<option value="3">Innovation</option>
<option value="8">Marketing</option>
<option value="9">Operations</option>
<option value="11">Research</option>
</select>
Here's the script:
var topicSelect = $("select");
var haveTopic = topicSelect.val("Not Here");
alert(haveTopic);
I'm expecting the alert to show "undefined" however it seems to be giving back the select
object. Is there a way I can check for the existence of an option without looping through every one?
Clarifications:
- string of text needs to be matched, not value
- looking for an开发者_如何学编程 exact, case sensitive match
- can return true/false or undefined
I believe this should find what you're looking for:
if ($("option:contains('not here')").length > 1) { }
The reason your original code didn't work is because you were setting the value attribute of the selector, and it was returning the select because jQuery methods will (almost) always returning the nodeset (in your case generated by "$('select')") so that the method can be integrated into a chain.
To test for a value:
var haveTopic = $("select option[value='not here']").length != 0
Edit
To test for text:
var haveTopic = $.inArray('Not Here',$("select").text().replace(/ /g,'').split("\n")) != -1
I haven't looked at how .filter(fn) is implemented, however you could use it as a solution.
$.fn.hasOptionWithText = function(text) {
var options = $("option", $(this)).filter(function(){
return $(this).text() === text;
});
return options.length > 0;
};
$(document).ready(function() {
var hasNotHere = $("select").hasOptionWithText('Not Here');
var hasGeneral = $("select").hasOptionWithText('General');
alert(hasNotHere + ' ' + hasGeneral);
});
精彩评论