The ^=
operator matches text at the start of the attribute, but it won't check that the rest is a valid number as such (is that important?). In theory:
if ($(this).find("option[text^='My Cool Option']").is(":selected"))
However! There is no text
attribute on option
, so both this and your original code shouldn't work. It only does work because of how jQuery fetches attribute values (fetching the text
property instead of the text
attribute), which is trying to work around some different browser bugs. This will definitely break in the future (if nothing else, when Selectors-API Level 2 is implemented in browsers and jQuery uses that in preference to its own code).
You could try the jQuery-specific non-standard contains
selector:
if ($(this).find('option:contains("My Cool Option")').is(":selected"))
but this could match that string elsewhere in the text, if that matters.
If you've got a non-multiple selectbox (ie. only one option may be selected), you can fetch the one selected option's text()
and check it:
if ($(this).find('option:selected').text().match(/^My Cool Option\d+$/))
otherwise, you'd have to iterate the options looking for the match:
var cool= false;
for (var i= this.options.length; i-->0;) {
var option= this.options[i];
if (option.selected && option.text.match(/^My Cool Option\d+$/)) {
cool= true;
}
}
if (cool) ...
(It's normally best to be checking option values rather than text strings though.)