使用jQuery,你如何检查选择菜单中是否有一个选项,如果没有,分配一个选择的选项。
(选择生成与一个应用程序的PHP函数的迷宫,我刚刚继承,所以这是一个快速修复,而我得到我的脑袋周围的那些:)
使用jQuery,你如何检查选择菜单中是否有一个选项,如果没有,分配一个选择的选项。
(选择生成与一个应用程序的PHP函数的迷宫,我刚刚继承,所以这是一个快速修复,而我得到我的脑袋周围的那些:)
当前回答
我发现了一个很好的方法来检查,如果选项被选中,并选择一个默认时,它不是。
if(!$('#some_select option[selected="selected"]').val()) {
//here code if it HAS NOT selected value
//for exaple adding the first value as "placeholder"
$('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
}
如果#some_select没有默认选择选项,则.val()是未定义的
其他回答
lencioni的答案是我推荐的。您可以使用“#mySelect option[value='yourDefaultValue']”更改选项的选择器('#mySelect option:last')来选择具有特定值的选项。更多关于选择器的信息。
如果你在客户端大量使用选择列表,请检查这个插件: http://www.texotela.co.uk/code/jquery/select/。如果您想看到更多使用选择列表的示例,请查看源代码。
不需要使用jQuery:
var foo = document.getElementById('yourSelect');
if (foo)
{
if (foo.selectedIndex != null)
{
foo.selectedIndex = 0;
}
}
如果你需要显式检查每个选项,看看是否有“selected”属性,你可以这样做。否则使用option:selected你将得到第一个默认选项的值。
var viewport_selected = false;
$('#viewport option').each(function() {
if ($(this).attr("selected") == "selected") {
viewport_selected = true;
}
});
你们选的人太多了。只需按值选择:
$("#mySelect").val( 3 );
更改选择框上的事件以触发,一旦它发生,则只需拉出所选选项的id属性:-
$("#type").change(function(){
var id = $(this).find("option:selected").attr("id");
switch (id){
case "trade_buy_max":
// do something here
break;
}
});