views:

567

answers:

4

I'm really new to HTML, but I can't find anywhere how to return the variable from a check box. I've figured out how to get variables from forms and inputs, but I don't know how to get them from check boxes. Basically, I want a check box that if checked, will return the value yes. If not checked, it doesn't have to return a value, but no would be nice.

+1  A: 

When submitting a form, if a checkbox is checked, it will be included in the values collection submitted to the server. If not checked, it will be omitted (as if that checkbox did not exist).

In JavaScript, you can find out whether the checkbox is checked by the checked property:

//returns true or false
var isChecked = document.getElementById('id_of_checkbox').checked;

In ASP.NET, the CheckBox control has a boolean property Checked.

Rex M
+1  A: 

Use the 'checked' property.

var checkbox = document.getElementById('checkboxId');
var checked = checkbox.checked;
Kevin Babcock
A: 

look at the value of YourCheckboxName.Checked

Chris Ballance
+2  A: 

Assign something to the value attribute. You should get the value of the checked box, if there is one in the form values on postback. Note that I've made it a radio input in the case where you want yes or no. For a radio you need to assign the same name, but different ids (if you assign an id at all). You'd want to use checkboxes in the case where you can have more than one value selected or only care to get the value when selected. These types of checkboxes should have different names.

<input type="radio" id="radio_yes" name="radio_btn" value="Yes" /> Yes
<input type="radio" id="radio_no" name="radio_btn" value="No"
       checked="checked" /> No

If you only want a single check box with the value yes to be returned if checked, then you can use a check box. You won't get any value if it isn't checked.

<input type="checkbox" id="chk_box" name="chk_box"
       value="Yes" /> Do you want this?

On the server-side, you look for the value corresponding to the "radio_btn" (first example) or "chk_box" (second example) key in your form parameters.

tvanfosson