29

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.

0

3 Answers 3

53

You forgot the # on the id selector:

if ($("#EventStartTimeMin").val() === "") {
    // ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

@RoryMcCrossan for .net if EventStartTimeMin where an asp.net control the code would be: if ($("#<%= EventStartTimeMin.ClientID %>").val() === "") { // ... }
@Juanito I know, but how is that relevant to this question?
For the negation of the expression, just use !==, of course.
Also note that if the default selected option is disabled, the value of the select element will be null instead.
9

You can try this also-

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

1 Comment

This might not be desired, e.g. in case when 0 is a valid option value.
5

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

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

Fiddle Demo

2 Comments

The problem with just using change is that if the last field requires keyboard input, there is no change until the viewer clicks on something, leaving them befuddled. Use .on('change, keyup',function(){ }) instead.
Yeah i noticed you have to put it inside a change. But why doesn't it work without a change? Nice answer btw!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.