:contains just isnt doing it for me here. Its too coarse. and I cant seem to figure out the right way to get it.
(.js fiddle below)
$(function() {
$('#my_button').click(function() {
var cookieVal = "ab"; //This is what I want to find
var select = "combo0";
var optionThatMatchesCookie = $("#" + select + " option:contains('" + cookieVal + "')").val();
alert(optionThatMatchesCookie); //returns the wrong entry! (returns 'cabd' not 'ab')
if (typeof(optionThatMatchesCookie) != "undefined") {
//now put that in the combobox
$('#' + select).val(optionThatMatchesCookie);
}
});
});
<select class="inputfield" id="combo0" name="jobType">
<option selected="selected">-select-</option>
<option id="1">sssssssssss</option>
<option id="18">fffffffffff</option>
<option id="47">cabd</option>
<option id="3">LPN/LVN</option>
<option id="22">bbbbb</option>
<option id="17">hhhhhhhhhh</option>
<option id="15">aaaaaaa</option>
<option id="16">zzzzzzzzzzzzzzz</option>
<option id="5">ab</option>
<option id="44">YYYYYYYYY</option>
<option id="19">XXXXXX</option>
</select>
<input type="button" id="my_button" value="test me"/>
It returns the
cabdoption because that contains “ab”, and that’s exactly what:containsis used for. If you’re wanting to return the value of theoptionthat exactly matches, you could usefilter:Here’s a working example.
As an aside, note that
typeofis an operator, not a method, so you shouldn’t put the operand in parentheses:Also note that you could shorten your code significantly to just this:
If
cookieValdoes not match the value of one of theoptionelements then the value will not change. See another working example here.