Jirka Kopřiva
Jirka Kopřiva

Reputation: 3099

jquery if - event shortcut exists?

I have a lot of condition in the code, where show/hide of elements depends if input value is not empty.

Does exist any shorter version for these lines?

if ($("input#x").val())
{
   $("#lbl_y").show();
}
else
{
   $("#lbl_y").hide();
}

Upvotes: 1

Views: 387

Answers (4)

Tats_innit
Tats_innit

Reputation: 34107

like this ternary operator you mean:

You can use .is(':empty') to do empty check!

var resultofexpression = conditionasboolean ? truepart: falsepart;

in your case:

$("input#x").is(':empty') ?   $("#lbl_y").show(); : $("#lbl_y").hide();

Upvotes: 1

Lix
Lix

Reputation: 47986

Essentially you could bring this down to one line -

($("input#x").val() == ''?  $("#lbl_y").show() :  $("#lbl_y").hide() )

I'm using here a ternary operator. In this case it behaves much like a simple conditional statement. It checks the evaluation of a certain condition and performs one task or another depending on the true/false value returned by the statement.

(condition ? true : false)

Upvotes: 1

webdeveloper
webdeveloper

Reputation: 17288

You can use such construction:

$("#lbl_y")[$("input#x").val() ? 'show' : 'hide']();

Upvotes: 1

zerkms
zerkms

Reputation: 255015

$("#lbl_y").toggle($("input#x").val());

Upvotes: 6

Related Questions