545

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?

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
Keith Donegan
  • 26,213
  • 34
  • 94
  • 129
  • 2
    [**The :empty pseudo-class represents any element that has no children** at all. Only element nodes and text (including whitespace) are considered. Comments or processing instructions do not affect whether an element is considered empty or not.](https://developer.mozilla.org/en/docs/Web/CSS/:empty) – Константин Ван Dec 23 '16 at 04:40

22 Answers22

857
$('#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).

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
164

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.

Alex Sexton
  • 10,401
  • 2
  • 29
  • 41
  • 19
    Absolutely right. Trimming is necessary, especially when using finicky WYSIWYG editors (like jWYSIWYG, for example). – Josh Smith Oct 29 '10 at 22:18
  • May I suggest changing value to val ---> if(!$.trim(this.val).length) { // zero-length string AFTER a trim $(this).parents('p').addClass('warning'); } – K. Kilian Lindberg Mar 20 '14 at 11:43
  • `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. – Alex Sexton Mar 31 '14 at 21:53
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..    
});
drewdeal
  • 371
  • 3
  • 2
24
if ($('input:text').val().length == 0) {
      $(this).parents('p').addClass('warning');
}
Graviton
  • 81,782
  • 146
  • 424
  • 602
  • Uncaught TypeError: Cannot read property 'length' of undefined – Chuck D Oct 04 '17 at 19:17
  • @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) {` – fWd82 Mar 20 '18 at 12:46
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');
    }
});
Zigri2612
  • 2,279
  • 21
  • 33
9

how come nobody mentioned

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

seems more jquery-like to me

Jamie Pate
  • 1,783
  • 20
  • 18
  • 3
    This doesn't work in jQuery 1.9+ since they changed how the selector filter works .. http://jsfiddle.net/6r3Rk/ – Wick Jul 31 '13 at 17:57
  • 3
    I suggest $(this).not('[value]').addClass('warning') for 1.9 http://jsfiddle.net/znZ9e/ – Jamie Pate Jul 31 '13 at 23:11
  • 1
    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. http://jsfiddle.net/T89bS/ ... the field without a value attribute gets slapped with salmon regardless if you type something in it. – Wick Nov 14 '13 at 19:48
7

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);
  });
Sonu Chohan
  • 141
  • 1
  • 5
  • Very flexible. This solution allows you to check for other things inside the on input instance. – klewis May 12 '22 at 19:55
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');
}});
Ouss Ama
  • 123
  • 3
  • 8
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

Dave Ward
  • 59,815
  • 13
  • 117
  • 134
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');
    }
});
xorinzor
  • 51
  • 1
  • 1
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');
     }
});
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
4

function checkForm() {
  return $('input[type=text]').filter(function () {
    return $(this).val().length === 0;
  }).length;
}
Vanilla
  • 112
  • 4
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
    }
}
Frankie Loscavio
  • 344
  • 4
  • 15
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

Mauro
  • 1,241
  • 22
  • 26
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.

Konstantine Kalbazov
  • 2,643
  • 26
  • 29
  • 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. – Fabian von Ellerts Sep 27 '18 at 14:25
2

try this:

function empty(){
        if ($('.text').val().length == 0)
        {
            alert("field should not be empty");
        }
    }
fazal
  • 43
  • 7
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>// :)
Maher
  • 2,517
  • 1
  • 19
  • 32
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>

Atlantiz
  • 39
  • 1
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.

Mark Carpenter Jr
  • 812
  • 1
  • 16
  • 32
1

A clean CSS-only solution this would be:

input[type="radio"]:read-only {
        pointer-events: none;
}
Dion
  • 3,145
  • 20
  • 37
1

Please use this code for input text

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

});

keivan kashani
  • 1,263
  • 14
  • 15
1
if($("#textField").val()!=null)

this work for me

Malek Tubaisaht
  • 1,170
  • 14
  • 16