549

I have a form that I would like all fields to be filled in. If a field is clicked into and then not filled out, I would like to display a red background.

Here is my code:

$('#apply-form input').blur(function () {
  if ($('input:text').is(":empty")) {
    $(this).parents('p').addClass('warning');
  }
});

It applies the warning class regardless of the field being filled in or not.

What am I doing wrong?

1

22 Answers 22

863
$('#apply-form input').blur(function()
{
    if( !$(this).val() ) {
          $(this).parents('p').addClass('warning');
    }
});

And you don't necessarily need .length or see if it's >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#apply-form input').blur(function()
{
    if( $(this).val().length === 0 ) {
        $(this).parents('p').addClass('warning');
    }
});

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#apply-form input').blur(function()
{
      if( !this.value ) {
            $(this).parents('p').addClass('warning');
      }
});

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element (provided there's one textfield in the context's descendants/children).

Sign up to request clarification or add additional context in comments.

2 Comments

$(this).val().length < 1
YourObjNameSpace.yourJqueryInputElement.keyup(function (e){ if($.trim($(this).val())){ // trimmed value is truth }else{ // trimmed value is falsey } }
167

Everybody has the right idea, but I like to be a little more explicit and trim the values.

$('#apply-form input').blur(function() {
     if(!$.trim(this.value).length) { // zero-length string AFTER a trim
            $(this).parents('p').addClass('warning');
     }
});

if you dont use .length , then an entry of '0' can get flagged as bad, and an entry of 5 spaces could get marked as ok without the $.trim . Best of Luck.

3 Comments

Absolutely right. Trimming is necessary, especially when using finicky WYSIWYG editors (like jWYSIWYG, for example).
May I suggest changing value to val ---> if(!$.trim(this.val).length) { // zero-length string AFTER a trim $(this).parents('p').addClass('warning'); }
this.val would be undefined there. It'd need to be $(this).val() - but there's no cross-browser advantage to that, so I left it out for brevity/speed.
37

Doing it on blur is too limited. It assumes there was focus on the form field, so I prefer to do it on submit, and map through the input. After years of dealing with fancy blur, focus, etc. tricks, keeping things simpler will yield more usability where it counts.

$('#signupform').submit(function() {
    var errors = 0;
    $("#signupform :input").map(function(){
         if( !$(this).val() ) {
              $(this).parents('td').addClass('warning');
              errors++;
        } else if ($(this).val()) {
              $(this).parents('td').removeClass('warning');
        }   
    });
    if(errors > 0){
        $('#errorwarn').text("All fields are required");
        return false;
    }
    // do the ajax..    
});

Comments

26
if ($('input:text').val().length == 0) {
      $(this).parents('p').addClass('warning');
}

2 Comments

Uncaught TypeError: Cannot read property 'length' of undefined
@ChuckD I was getting same error and I figured out I was missing $ in if (('input:text').val().length == 0) { it should be if ($('input:text').val().length == 0) {
19

you can use also..

$('#apply-form input').blur(function()
{
    if( $(this).val() == '' ) {
          $(this).parents('p').addClass('warning');
    }
});

if you have doubt about spaces,then try..

$('#apply-form input').blur(function()
{
    if( $(this).val().trim() == '' ) {
          $(this).parents('p').addClass('warning');
    }
});

Comments

9

how come nobody mentioned

$(this).filter('[value=]').addClass('warning');

seems more jquery-like to me

3 Comments

This doesn't work in jQuery 1.9+ since they changed how the selector filter works .. jsfiddle.net/6r3Rk
I suggest $(this).not('[value]').addClass('warning') for 1.9 jsfiddle.net/znZ9e
I believe that only tests whether the field started out with a value attribute. It doesn't test the actual form field value like you'd need for validation. jsfiddle.net/T89bS ... the field without a value attribute gets slapped with salmon regardless if you type something in it.
8

how to check null undefined and empty in jquery

  $(document).on('input', '#amt', function(){
    let r1;
    let r2;
    r1 = $("#remittance_amt").val();
    if(r1 === undefined || r1 === null || r1 === '')
    {
      r1 = 0.00;
    }

    console.log(r1);
  });

1 Comment

Very flexible. This solution allows you to check for other things inside the on input instance.
6

The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)

    $("#inputname").keyup(function() {

if (!this.value) {
    alert('The box is empty');
}});

Comments

5

Consider using the jQuery validation plugin instead. It may be slightly overkill for simple required fields, but it mature enough that it handles edge cases you haven't even thought of yet (nor would any of us until we ran into them).

You can tag the required fields with a class of "required", run a $('form').validate() in $(document).ready() and that's all it takes.

It's even hosted on the Microsoft CDN too, for speedy delivery: http://www.asp.net/ajaxlibrary/CDN.ashx

Comments

5

There is one other thing you might want to think about, Currently it can only add the warning class if it is empty, how about removing the class again when the form is not empty anymore.

like this:

$('#apply-form input').blur(function()
{
    if( !$(this).val() ) {
          $(this).parents('p').addClass('warning');
    } else if ($(this).val()) {
          $(this).parents('p').removeClass('warning');
    }
});

Comments

4

The :empty pseudo-selector is used to see if an element contains no childs, you should check the value :

$('#apply-form input').blur(function() {
     if(!this.value) { // zero-length string
            $(this).parents('p').addClass('warning');
     }
});

Comments

4

function checkForm() {
  return $('input[type=text]').filter(function () {
    return $(this).val().length === 0;
  }).length;
}

Comments

3

Here is an example using keyup for the selected input. It uses a trim as well to make sure that a sequence of just white space characters doesn't trigger a truthy response. This is an example that can be used to begin a search box or something related to that type of functionality.

YourObjNameSpace.yourJqueryInputElement.keyup(function (e){
   if($.trim($(this).val())){
       // trimmed value is truthy meaning real characters are entered
    }else{
       // trimmed value is falsey meaning empty input excluding just whitespace characters
    }
}

Comments

3
$(function() {
  var fields = $('#search_form').serializeArray();
  is_blank = true;
  for (var i = 0; i < fields.length; i++) {
    // excluded fields
    if ((fields[i].name != "locale") && (fields[i].name != "utf8")) {
      if (fields[i].value) {
        is_blank = false;
      }
    }
  }
  if (is_blank) {
    $('#filters-button').append(': OFF');
  }
  else {
    $('#filters-button').append(': ON');
  }
});

Check if all fields are empty and append ON or OFF on Filter_button

Comments

3

try this:

function empty(){
        if ($('.text').val().length == 0)
        {
            alert("field should not be empty");
        }
    }

Comments

2

You can try something like this:

$('#apply-form input[value!=""]').blur(function() {
    $(this).parents('p').addClass('warning');
});

It will apply .blur() event only to the inputs with empty values.

1 Comment

Good solution, but be warned this only works if the input is not empty upon function call and also only if the value is saved in the input's "value" attribute.
1
<script type="text/javascript">
$('input:text, input:password, textarea').blur(function()
    {
          var check = $(this).val();
          if(check == '')
          {
                $(this).parent().addClass('ym-error');
          }
          else
          {
                $(this).parent().removeClass('ym-error');  
          }
    });
 </script>// :)

1 Comment

You probably need to trim the whitespace as well.
1

Great collection of answers, would like to add that you can also do this using the :placeholder-shown CSS selector. A little cleaner to use IMO, especially if you're already using jQ and have placeholders on your inputs.

if ($('input#cust-descrip').is(':placeholder-shown')) {
  console.log('Empty');
}

$('input#cust-descrip').on('blur', '', function(ev) {
  if (!$('input#cust-descrip').is(':placeholder-shown')) {
    console.log('Has Text!');
  }
  else {
    console.log('Empty!');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="form-control" id="cust-descrip" autocomplete="off" placeholder="Description">

You can also make use of the :valid and :invalid selectors if you have inputs that are required. You can use these selectors if you are using the required attribute on an input.

Comments

1

A clean CSS-only solution this would be:

input[type="radio"]:read-only {
        pointer-events: none;
}

Comments

1

Please use this code for input text

$('#search').on("input",function (e) {

});

Comments

1
if($("#textField").val()!=null)

this work for me

Comments

1

With HTML 5, we can use a new feature "required" the just add it to the tag which you want to be required like:

<input type='text' required>

2 Comments

And all browser don't support this... You have to add a js check AND a serverside check
Question title, "Check if inputs are empty using jQuery"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.