开发者

javascript if - else shortcut doesn't work?

开发者 https://www.devze.com 2023-01-07 20:19 出处:网络
I have a checkbox couple with values \"new\" or \"existing\" company. $开发者_高级运维(\"input[name=company]:checked\").val()

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?


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";


Try

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


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

精彩评论

暂无评论...
验证码 换一张
取 消