views:

54

answers:

3

I have a checkbox couple with values "new" or "existing" company.

$("input[name=company]:checked").val()

with jQuery shows me the value of the checked box.
Now if I do:

if ($("input[name=company]:checked").val() == "new") {
    is_new_company = true;
} else { 
    is_new_company = false; 
}
alert(is_new_company);

I get the correct booleans.
Doing the shortcut:

($("input[name=company]:checked").val() == "new") ? is_new_company = true : is_new_company = false;

I get nothing.. Why is that?

A: 

Try

is_new_company = ($("input[name=company]:checked").val() == "new") ?  true : false;
Salil
-1: `condition ? true : false` is redundant and should really just be replaced by `condition`.
Amber
@Amber Downvotes seem a bit harsh; the answers are right, just (slightly) unnecessarily verbose
Michael Mrozek
@Michael: I never mind removing downvotes if someone replies to a comment stating they fixed the redundancy, but I will downvote in the first place if it's redundant code, because redundant code is poor code.
Amber
A: 
is_new_company = ($("input[name='company']:checked").val() == "new") ? true : false;
Sadat
-1: `condition ? true : false` is redundant and should really just be replaced by `condition`.
Amber
@Amber, ans is correct. Please downvote after testing.
Sadat
I know that it operates correctly, that was not the reason for downvoting. The downvote was due to bad style.
Amber
workout properly is first, beauty is additional- :)
Sadat
+3  A: 

Why don't you just do:

is_new_company = $("input[name=company]:checked").val() == "new";

I tried your code on Firebug console and it works fine: (input[name=q] is the search box at the top right corner of this page)

var x;
$("input[name=q]").val() == "asd" ? x = "t r u e" : x = "f a l s e";
console.log(x);//worked as expected

By the way, I consider the following to be more readable (I'd use it only for non-boolean values, of course):

x = $("input[name=q]").val() == "asd" ? "t r u e" : "f a l s e";
Amarghosh