-1

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!?

1
  • Did you bind this function to textarea event? Because if you do then you don't need use $('textarea: name') selector, you'll have already 'this'. Commented Jun 15, 2011 at 18:23

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Also the selector. What is $('textarea: name') supposed to be?
Thanks! Closing parens in place!
2

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]')

3 Comments

Nice! That worked as I wanted, but I was using the ID of the textarea not the name from the beginning. ID not working like this $('textarea[#yourName]')?
You could do $('textarea#yourName') or just $('#yourName'). The second one will perform faster.
Yes, @justis's method is perfect. However, just so you're clear on what I was doing, $('textarea') will select all textarea elements in the document. If you want to select an element by it's id, you use the #. If you want to use the class, you use a ., and if you want to use another attribute you do it like this: $('textarea[name=theName]').
2

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.