1

I take a form and wants value of checkbox. such as:

<form method="post" onSubmit="return nameempty()">

<input name="checkn1" id="check1" type="checkbox" />
<input name="checkn2" id="check2" type="checkbox" />

<input type="submit" value="submit">
</form> 

Now I want to know the values of checkbox when it is selected, and also when not selected.

Now I write javascript, and get that each checkbox has value "on" whether it is selected or not.

<script>
function nameempty()
{
alert(document.getElementById('check1').value);
alert(document.getElementById('check2').value);
}
</script>

How could I get 'on' when it is selected and anything else when not selected.

1
  • I am new in this line Commented Feb 2, 2014 at 11:32

2 Answers 2

1

use checked instead of value which will return true if the checkbox is checked or it will return false

<script>
function nameempty()
{
alert(document.getElementById('check1').checked);
alert(document.getElementById('check2').checked);
}
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

One way to get the value of a 'checked' check box which includes the check if 'checked'

var check1value = document.querySelector('#check1:checked').value;

In the html you are missing a value attribute (if checked)

<input name="checkn1" id="check1" value="value-here" type="checkbox" />

2 Comments

how could I get "off" when not selected ?
Actually when second box is selected and first is not selected then no alert is shown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.