JQuery: text field is empty or not

I have several text fields on the page, imagine 10, 4 of these 10 have the class "myClass". I would like to know if ALL of these text fields with class "myClass" have length = 0, in one line the command

Possible?

Thanks,

Update1

function MyValidation() { var res = true; if (!$("input:text.MyClass[value!='']").length) { alert("testing"); res = false; } return res; } 

When you get this code, I get โ€œtrueโ€ all the time, never โ€œfalseโ€ and never โ€œcheckโ€. I tried the code for each answer.

+4
source share
4 answers

that should be enough

 if ( $('.myClass').filter(function(){ return $(this).val() != ''; }).length == 0 ) { /* code to run when all are empty */ } 

demo http://jsfiddle.net/gaby/QasRK/


To accommodate white space when changing a line

 return $(this).val() != ''; 

to

 return $(this).val().replace(/\s/g,'') != ''; 

This removes the space text before matching it with ''

+5
source

You can write

 if (!$(input.myClass).is(function() { return this.value.length > 0; })) 
+1
source

This can also be done using the appropriate attribute selector :

 if (!$("input:text.myClass[value!='']").length) { // All the .myClass text boxes are empty. } 
+1
source

If you want the values:

 var any = $("input:text.myClass").map(function() { var value = $.trim($(this).val()); if (value != "") return value; }).length > 0; 

http://jsfiddle.net/hunter/e6yEd/


If you do not:

 var any = $("input:text.myClass").filter(function() { return $.trim($(this).val()) != ""; }).length > 0; 

http://jsfiddle.net/hunter/e6yEd/5/

0
source

All Articles