TheBoubou
TheBoubou

Reputation: 19903

jQuery : Textbox empty or not

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

Possible?

Thanks,

Update1

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

When you this code, I receive a "true" all the time never "false" and never "testing". I tried the code of every answer.

Upvotes: 4

Views: 4770

Answers (4)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

this should suffice

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

 }

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


To accommodate for white-space in the string change

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

to

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

This strips the text of white-space before comparing it to ''

Upvotes: 5

hunter
hunter

Reputation: 63512

If you want to 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 don't:

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

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

Upvotes: 0

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

That can also be done with the appropriate attribute selector:

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

Upvotes: 1

SLaks
SLaks

Reputation: 887305

You can write

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

Upvotes: 1

Related Questions