views:

1848

answers:

7

How can you say the following in jQuery?

If If textarea AND input.title are NOT empty, then put input.button ON.

My attempt in pseudo-code

if ( $(textarea).not.empty() AND $(input.title).not.empty() ) {
   $('.ask_question').attr('enabled, 'enabled'); 
}
A: 
if ( $("textarea").val() != "" && $("input.title").val() != "" ) {
   $('.ask_question').attr('enabled', 'enabled'); 
}
stefita
You're missing a quote there: should be `attr('enabled', 'enabled')`.
John Feminella
$(textarea).value() - value() isn't a jQuery method - it's val(). Also the selectors should be enclosed in quotes and ideally only return a single item.
Sohnee
`.attr('enabled', true)` works too.
nickf
A: 
if ($("#myTextArea").val().length != 0 AND $("#myTextBox").val() != 0) {
   $('.ask_question').removeAttr("disabled"); 
}

You can use "textarea" and "input[class='title']", but it is possible for these to return multiple results.

Sohnee
Your code seems to need this `.length` after the second `.val()`. However, I have not yet managed to get your code to work with or without the addition.
Masi
Well spotted, it does need .length after val(). Do you get an error or unexpected results?
Sohnee
A: 

Not too far off.

if ( $("textarea").val().length && $("input.title").val().length ) {
  $('.ask_question').removeAttr('disabled'); 
}
Andy Gaskell
Shouldn't you be comparing the length to something - or are you relying on 0 being implicitly converted to false?
Sohnee
Try it out :)
Andy Gaskell
Yes - I was trying to point out rhetorically that an implicit cast of an integer to boolean isn't very nice.
Sohnee
I think it's very nice!
Andy Gaskell
@andy, i totally agree. having `0 == false` is a very hand shortcut, which cuts a lot of useless verbosity from your code.
nickf
+1  A: 
if ( $("textarea:empty").length == 0 && $("input.title:empty").length == 0 ) {
   $('.ask_question').attr('enabled', 'enabled'); 
}

The method property length of jQuery returns the number of elements which were selected. :empty is a selector for jQuery to select elements which have no child or no text.

So,

if (number of empty textarea is 0) AND (number of empty input with the class title is 0) then
   enable somthing!
Mike
`length` is a property, not a method.
nickf
Firebug gives me the following error for your code: `$("textarea:empty").length is not a function`
Masi
Thanks nickf, have overseen that one
Mike
+3  A: 

What would jQuery-jesus do?

$('textarea').is(":contains('')")

or

$('input.title').is(":empty")

I suppose ;)

Mickel
This solution is actually better than mine :)
Mike
Does that work like an IF statement? If so, it seems less readable.
Nathan Long
jQuery.is() returns a boolean and I'd say that it's very readable :)
Mickel
A: 

This sites's great!

Imageizing
A: 

I'm amazed at how much I can learn from visitors by adding additional blog features!

Imageizing