I have the following statement:
if ($(this).find("option[text='My Cool Option1']").is(":selected"))
//do something
basically I have a combobox with many options. I want to do something for options that start with My Cool Option<any number>
above code works for only one option My Cool Option1…but how do I make it work for say My Cool Option2 ..3..4 etc.
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:However! There is no
textattribute onoption, so both this and your original code shouldn’t work. It only does work because of how jQuery fetches attribute values (fetching thetextproperty instead of thetextattribute), 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
containsselector: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:otherwise, you’d have to iterate the options looking for the match:
(It’s normally best to be checking option values rather than text strings though.)