Reputation: 60027
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:
Upvotes: 1
Views: 1021
Reputation: 1455
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.
Upvotes: 1
Reputation: 108517
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
Upvotes: 1
Reputation: 645
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);
});
Upvotes: 0