Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select empty inputs (value="") using jQuery

People also ask

How check input field is empty in jQuery?

To check if the input text box is empty using jQuery, you can use the . val() method. It returns the value of a form element and undefined on an empty collection.


jQuery("#sender_container input.required").filter(function() {
    return !this.value;
}).addClass("error");​

Why you have to use filter and not [value=""] you can see in this DEMO

The reason is: attribute selectors check the initial state of the element, not the current state. (note that you can change the "initial" state with the attr function, but it's bad practice, you should always use prop)

So if you change the input value, the current value won't effect the attribute selector. not wise... :)

Notes:

  • .val() returns the value of the form element, and breaks the jQuery chain, $('selector').val().addClass('foo') Error, the return value is a string\ number

  • .val(valueToSet) sets the value of the form element and doesn't break the jQuery chain.
    $('selector').val("some value").addClass('foo') - Valid, the returned value is a jQuery


$('input:text[value=]','#sender_container').addClass('error');

DEMO


$('#sender_container input.required[value=""]').addClass('error')

jQuery('#sender_container input.required[value=""]').addClass("error");

You can try this:

$('input:not([value!=""])').addClass('error');

DEMO

Note: This answer should not be used, and the only reason it wasn't deleted is so it can be learned from.