Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check all input fields have been filled out with jQuery

I have 3 divs, each with a dfew input fields and next button on. I want to write a snippet of jQuery that when the next button is clicked it checks to ensure all input fields WITHIN the same div as the button, are not null.

I've tried the following with no luck but Im 100% certain its wrong, only I cant find the relevant information online...

http://jsfiddle.net/xG2KS/1/

like image 764
Liam Avatar asked Jan 18 '12 09:01

Liam


People also ask

How do you check if all inputs are filled jQuery?

Just use: $("input:empty"). length == 0; If it's zero, none are empty.

How check input field is empty or not 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.


2 Answers

You could use filter to reduce the set of all input elements to only those that are empty, and check the length property of what remains:

$(".next").click(function() {     var empty = $(this).parent().find("input").filter(function() {         return this.value === "";     });     if(empty.length) {         //At least one input is empty     } }); 

Note that the definition of empty in the above code is an empty string. If you want to treat blank spaces as empty too, you may want to trim the value before comparing.

Also note that there is no need to pass this into jQuery inside the filter function. The DOM element itself will have a value property, and it's much faster to access that instead of using val.

Here's an updated fiddle.

like image 167
James Allardice Avatar answered Oct 11 '22 05:10

James Allardice


$('.next').click(function() {     var emptyInputs = $(this).parent().find('input[type="text"]').filter(function() { return $(this).val() == ""; });     if (emptyInputs.length) {         alert('Fail!');     } }); 
like image 26
Alex Pliutau Avatar answered Oct 11 '22 04:10

Alex Pliutau