Javascript jQuery获取选择选项值为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7880846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery get select option value empty
提问by TuanNguyen
<select name="category" id="category">
<option value="">All Category</option>
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
How to choose the category with value=""
如何选择 value="" 的类别
Conditions for a correct:
正确的条件:
if($('#category option:selected')){
var category_url = "&category="+$('#category').val(); <!-- True -->
}
Condition 2 wrong:
条件2错误:
if($('#category option[value=""]')){
var category_url = ""; <!-- Error -->
}
Please help me!!!
请帮我!!!
回答by legendofawesomeness
I am not sure if I understand your question correctly, but are you looking to do something like this?
我不确定我是否正确理解您的问题,但您是否想做这样的事情?
if($('#category option:selected')){
var selValue = $('#category').val();
var category_url;
if(selValue)
category_url = "&category="+$('#category').val(); <!-- True -->
else
<!-- error -->
}
回答by CW30Meters
if(!$("#category").val())
//selected valule is ""
回答by Gavin M. Roy
This is a bit old, but you could do:
这有点旧,但你可以这样做:
$('#category').find('option:empty')
回答by Robin Rumeau
In fact, if you tell the browser to select nothing, it does the jox :
事实上,如果你告诉浏览器什么都不选,它会执行 jox :
$("#category option").attr("selected", false); //Unselect each option
By default the browser Will select will show the first option, whatever is the option's value.
默认情况下,浏览器将选择将显示第一个选项,无论选项的值是什么。
Hope this will helps :)
希望这会有所帮助:)
回答by Yogesh Gadade
The question is too old. But it can be useful for other people.
这个问题太老了。但它可能对其他人有用。
$( <selector> ).find('option[value="<required-value>"]').attr('selected','selected')
$( <selector> ).find('option[value="<required-value>"]').attr('selected','selected')