How do I change a variable based on a checkbox during validation
I've successfully pulled the checked value from a radio button group with jQuery 1.4 using the fo开发者_开发问答llowing code:
var myFirstVar = $("input[name='myFirstVar']:checked").val();
How would I alter this code to find out whether a check-box was checked, and to change the value of the var based on whether it is checked or not.
I tried many things, but here is an example of what I thought would work:
if ($("input[name='mySecondVar']:checked")) {
var mySecondVar = "Yes";
}
else {
var mySecondVar = "No";
}
Any insight on simply changing the value whether the box is checked or not would be great.
Try this:
var mySecondVar = $("input[name='mySecondVar']:checked").length ? "Yes" : "No";
The ":checked" part of the selector is just telling jQuery to only select items that are checked. jQuery selectors always return a result (the jQuery object), so simply putting the selector in the if clause isn't sufficient. You want to see whether the result actually included any elements, so $("input[name='mySecondVar']:checked").length
will work for your conditional clause (since Javascript interprets 0 as "false").
Another approach would be
if ($("input[name='mySecondVar']")[0].checked) {
var mySecondVar = "Yes";
}
else {
var mySecondVar = "No";
}
You can set your java script variable's based on condition.
if($("input[name='testVar']:checked").length)
set variable
else
set variable
精彩评论