Richard
Richard

Reputation: 1464

jquery each() function not working as intended

I'm trying to loop through all the inputs in my form and if the input does not contain a value, then do a couple of things.

Here's my code so far,

$('input').each(function() {
    if($(this+'[value!=""]')) {
        $('.requiredMark').hide();
        $(this).after(checkMark);   
    }       
});

What am I doing wrong? Thank you

Upvotes: 0

Views: 89

Answers (5)

AlexC
AlexC

Reputation: 9661

$('input').val(function(index,el){
    if(el.length){
        alert('Has value')
    }
});

http://jsfiddle.net/VpmAv/

Upvotes: 0

zhujy_8833
zhujy_8833

Reputation: 571

Instead of doing $(this+'[value!=""]'), you can use

if($(this).val()===''){
   //if the element has empty value, do something here
}

Upvotes: 1

Dany Y
Dany Y

Reputation: 7031

You can access your input field with $(this)

to get its value its $(this).val()

Upvotes: 0

Mat Richardson
Mat Richardson

Reputation: 3606

This should do the trick.

 $('input').each(function(){
            if($(this).val()){
                $('.requiredMark').hide();
                $(this).after(checkMark);   
            }       
      });

Upvotes: 0

alexn
alexn

Reputation: 58962

That if-statement is wrong. this will not refer to a string. Use .val() to get the value:

 $('input').each(function(){
     var $this = $(this);

     if($this.val() != "") {
         $('.requiredMark').hide();
         $this.after(checkMark);   
     }       
 });

Upvotes: 1

Related Questions