Reputation: 3099
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
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
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
Reputation: 17288
You can use such construction:
$("#lbl_y")[$("input#x").val() ? 'show' : 'hide']();
Upvotes: 1