if option-text isn't CSS then select it
$("select[name=lang] > option").each(function() {
if ($(this).text() == "CSS"){
$("select[name=lang]").val($(this).val());
}
}开发者_JS百科
<select name=lang>
<option value=0>Select
<option value=1>HTML
<option value=2>CSS
<option value=3>PHP
</select>
i want to check all options and select by optiontext. best regards
If you want to select the option with text 'CSS' (which I conclude from your code although your question states otherwise), with proper HTML markup
<select name="lang">
<option value=0>Select</option>
<option value=1>HTML</option>
<option value=2>CSS</option>
<option value=3>PHP</option>
</select>
your code works fine: http://jsfiddle.net/fkling/sSRDR/
Proper markup in this case means:
- attributes in quotes
- closing
option
tags
Normally you don't have to have closing tags (although there is no reason to not have them), the browser will insert them for you, but in this case if you don't put them, the browser will generate
<option value=2>CSS
</option>
which means the text inside the option is "CSS\n"
(CSS
+ line break) and this will never be equal to solely "CSS"
.
However, if you can exclude that the text you are searching for can occur in other elements, you can use :contains()
:
$('option:contains(CSS)').attr('selected', true);
On the other hand, if you want to select everything that is not "CSS", then you need a multiple select
box, as a normal select
can only have one selected option:
<select multiple="multiple" name="lang">
and you can use .filter()
to filter out the options:
$('select[name="lang"] > option').filter(function() {
return $(this).text() !== "CSS";
}).attr('selected', true);
DEMO
$("select[name=lang] > option").click(function(e) {
if ($(e.target).text() == "CSS"){
return false;
}
}
精彩评论