Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all inputs are not empty with jQuery

Tags:

jquery

input

I need to validate a form with jQuery. I can check all my inputs one by one, but it's not a very practical solution.

How can i check if all my inputs are non-empty more efficiently? In my form i can have input elements of different types: text, several groups of radio, select etc.

like image 950
Clément Andraud Avatar asked Apr 25 '13 10:04

Clément Andraud


People also ask

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.

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

Just use:

$("input:empty").length == 0; 

If it's zero, none are empty.

To be a bit smarter though and also filter out items with just spaces in, you could do:

$("input").filter(function () {     return $.trim($(this).val()).length == 0 }).length == 0; 
like image 152
mattytommo Avatar answered Sep 28 '22 01:09

mattytommo


Use each:

var isValid; $("input").each(function() {    var element = $(this);    if (element.val() == "") {        isValid = false;    } }); 

However you probably will be better off using something like jQuery validate which IMO is cleaner.

like image 41
Darren Avatar answered Sep 28 '22 01:09

Darren