简体   繁体   中英

having trouble with html checkbox

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

因为ID属性应该是唯一的,所以document.getElementById返回第一个匹配的元素。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM