使用jQuery检查选定的下拉列值是否为空

时间:2022-12-18 20:26:00

Here is the dropdown in question:

以下是问题的下拉列表:

<select name="data" class="autotime" id="EventStartTimeMin">
    <option value=""></option>
    <option value="00">00</option>
    <option value="10">10</option>
    <option value="20">20</option>
    <option value="30">30</option>
    <option value="40">40</option>
    <option value="50">50</option>
</select>

What I want to do is check if the current value is empty:

我想要做的是检查当前值是否为空:

if ($("EventStartTimeMin").val() === "") {
   // ...
}

But it does not work, even though the value is empty. Any help is much appreciated.

但即使值为空,它也不起作用。任何帮助深表感谢。

3 个解决方案

#1


30  

You forgot the # on the id selector:

你忘记了id选择器上的#:

if ($("#EventStartTimeMin").val() === "") {
    // ...
}

#2


5  

You can try this also-

你也可以试试这个 -

if( !$('#EventStartTimeMin').val() ) {
// do something
}

#3


3  

You need to use .change() event as well as using # to target element by id:

您需要使用.change()事件以及使用#来按ID来定位元素:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

#1


30  

You forgot the # on the id selector:

你忘记了id选择器上的#:

if ($("#EventStartTimeMin").val() === "") {
    // ...
}

#2


5  

You can try this also-

你也可以试试这个 -

if( !$('#EventStartTimeMin').val() ) {
// do something
}

#3


3  

You need to use .change() event as well as using # to target element by id:

您需要使用.change()事件以及使用#来按ID来定位元素:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo