Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if inputs are empty using jQuery

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?

like image 481
Keith Donegan Avatar asked Dec 06 '09 06:12

Keith Donegan


People also ask

How check multiple textbox is empty or not in jQuery?

click(function(e) { var isValid = true; $('input[type="text"]'). each(function() { if ($. trim($(this). val()) == '') { isValid = false; $(this).


2 Answers

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.

like image 23
Alex Sexton Avatar answered Oct 11 '22 21:10

Alex Sexton


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

like image 89
meder omuraliev Avatar answered Oct 11 '22 19:10

meder omuraliev