Fran Herruzo
Fran Herruzo

Reputation: 1

Error addClass Jquery

I use bootstrap and Jquery 2.0, and when i try to submit a form add class "error" if the form is invalid. I dont know why this didn't work.Can you help me?

     function validate(){   
         if (isEmpty($('inputName').value)){
             $("#name").addClass("error");
             }
         }


     function isEmpty(texto){
        if (texto == null || texto.length==0 || /^\s+$/.test(text))
            return true;
        else 
            return false;
    }

EDIT:

Why this work?

     function validate(){   
         if (isEmpty($('inputName').value)){
             alert("error");
             }
         }

And the addclass dont work:

     function validate(){   
         if (isEmpty($('inputName').value)){
             $("#name").addClass("error");
             }
         }

HTML:

      <div class="control-group" id="name">
        <label class="control-label" for="input">Name</label>
        <div class="controls">
          <input type="text" id="inputName" placeholder="Name">
        </div>
      </div>

Upvotes: 0

Views: 453

Answers (3)

Musa
Musa

Reputation: 97672

The jQuery object has no value property, what you want is the val method. Also $('inputName') would try to select a <inputName> element which you probably don't have, if inputName is an id the you can do

 isEmpty($('#inputName').val())

Upvotes: 3

Paweł Szymański
Paweł Szymański

Reputation: 7792

You may replace

(texto == null || texto.length==0 || /^\s+$/.test(text))

with

$.trim(texto) === ''

Also don't ever use == or !=, use === and !== instead.

Upvotes: 0

Seiyria
Seiyria

Reputation: 2132

Try comparing against $("#inputName").val() (notice the parenthesis). What you're doing is checking for the existence of a value attribute, which might be there, or it might not be, but it's not the value of the value, if that makes sense.

Upvotes: 3

Related Questions