0

I can't figure out why my checkbox is always evaluating to "yes" regardless of what is checked.

the html:

<input type="checkbox" name="email" id="email" value="yes">Yes<br>
<input type="checkbox" name="email" id="email" value="no" checked >No<br>

which is being accessed by

var email = document.getElementById('email').value;

and the php is just $_GET-ing the value of 'email' but it always processes it as it being set to "yes".

2
  • You should have a unique id for every html element. Thus, since you have two id="email", this is not good. Commented Nov 6, 2011 at 23:16
  • Note also that the value of unchecked checkboxes doesn't get submitted so if neither box is checked you won't get "yes" or "no" in your PHP. Though I don't think it makes sense for a yes/no option to allow neither to be selected, so why aren't you using radio buttons for this? Commented Nov 6, 2011 at 23:35

3 Answers 3

6

Because ID attribute should be unique, and document.getElementById returns first matched element.

Sign up to request clarification or add additional context in comments.

2 Comments

I just have a question; I added if(document.getElementById('email').checked == true) { var email = document.getElementById('email').value; } to check the checkboxes, but it has slowed down processing by a lot, and I'm curious why.
I doubt that only this slowed down your processing, maybe there are some parts that executes because variable email was set? By the way your approach to dealing with checkboxes will be highly ineffective for more than 2 choices, instead of assigning id to them, assign ID to form element and iterate through it's elements using inputs name to check which one is checked.
1

Its true that you should be using radio buttons if you only want a yes/no answer, have you used checkboxes intentionally? The radio button code would look like this as you wrote for the checkboxes:

PHP:

<?PHP
$selected_radio = $_POST['answer'];
print $selected_radio;
?>

HTML:

<FORM name ="form1" method ="post" action ="radioButton.php">
 <Input type = 'Radio' Name ='answer' value= 'Yes'>Yes
 <Input type = 'Radio' Name ='answer' value= 'No'>No
 <Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
</FORM>

If you really want to use checkboxes, then give them separate ID's and check them individually:

HTML:

<input type="checkbox" name="email" id="email_yes" value="yes">Yes<br>
<input type="checkbox" name="email" id="email_no" value="no" checked >No<br>

JS:

var email = (document.getElementById('email_yes').value == 1) 'yes' : 'no';

Comments

-1

Simply put, because it's a checkbox. A radio button (type="radio") is the type which enforces only one of the boxes in a group can be checked, and is probably what you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.