3D-kreativ
3D-kreativ

Reputation: 9301

If statement in Javascript?

Is this code correct?

if(!($('textarea: name').val().length == 0)) {
alert("test");
}

I want to check if there is something written or not inside the textarea field in the form? I ask because it's not working!?

Upvotes: 0

Views: 207

Answers (4)

justis
justis

Reputation: 504

Since a length of 0 is "falsy", you can simplify your test to using just .length:

if ($('textarea[name=foo]').val().length) {
    alert(true);
} else {
    alert(false);
}

Here is a jsFiddle where you can play with it.

Upvotes: 2

James Allardice
James Allardice

Reputation: 165941

if(!($('textarea').val().length == 0)) will work if you have only one textarea element in your page. I think what you were trying to do with that :name selector was select a specific textarea based on its name, in which case you need:

$('textarea[name=yourName]')

Upvotes: 2

Thomas
Thomas

Reputation: 1197

if ($('textarea: name').val().length > 0) {
    // do something if textbox has content
}

Upvotes: 0

p.campbell
p.campbell

Reputation: 100557

You're missing your closing parens in your if statement. Try this:

 if(!( $('textarea: name').val().length == 0 ))
   {alert("test");}

There may be other jQuery selector issues.

Upvotes: 4

Related Questions