jQuery 如果select有选项,如何使用jquery检查?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4972031/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:18:53  来源:igfitidea点击:

How to check with jquery if select has options?

jqueryhtml

提问by George

How to check with jquery if select has options and if it doesn't to disable it and show [not items]?

如何使用jquery检查select是否有选项,如果没有禁用它并显示[not items]?

回答by Nathan Anderson

One way to do to it:

一种方法:

if ($('#myselect option').length == 0) {
    $('#myselect').hide();
}

回答by jAndy

var $select = $('input:select option');
if(!$select.length )
    $select.attr('disabled', true);
var $select = $('input:select option');
if(!$select.length )
    $select.attr('disabled', true);

Or:

或者:

$('select:not(:has(option))').attr('disabled', true);

回答by ScottyG

Another way to do it is simply use the jQuery hasfunction

另一种方法是简单地使用 jQuery has函数

if ($('#myselect').has('option').length == 0) 
{
    // Hide and disable select input here
}

For information on the jQuery hasfunction see: https://api.jquery.com/has/

有关 jQuery has函数的信息,请参见:https: //api.jquery.com/has/

回答by Jamiec

select:not(:has(option))

is the selector you'd be looking for. You can use it to find the empty select boxes, disable them, and then append an option saying "No option available" or some such message - like so:

是您要寻找的选择器。您可以使用它来查找空的选择框,禁用它们,然后附加一个选项,说明“无选项可用”或一些此类消息 - 如下所示:

var noOptions = $('<option/>').html('No options');
$('select:not(:has(option))').attr('disabled',true).append(noOptions);

Live example here: http://jsfiddle.net/f3myz/

现场示例:http: //jsfiddle.net/f3myz/

回答by ga6ix

if you have the empty option, then you can:

如果您有空选项,那么您可以:

#Allways you must have the empty option
if ($("select#your_class").children().size() == 1) {
  alert("Without options")
  $("select#your_class").hide()
} else {
  alert("With options")
  $("select#your_class").show()

回答by Luis Leon Gonzalez

I tested this and it worked perfectly, hope it helps:

我对此进行了测试,效果很好,希望对您有所帮助:

if($("#myselect").html() == ""){
    $("#myselect").html("<option>[not items]</option>");
    $("#myselect").addProp("disabled","disabled");
}

回答by tarek shaheen

$('select.class>option').size()

OR if your select has an id not a class

或者,如果您的选择有一个 id 而不是一个类

$('select#id>option').size()

it will show you how many options inside

它会告诉你里面有多少选项