The values of the checkboxes are not getting stored. When i alert the values in place of selected += elements[i].value + "\\n"; i am getting the values.
<script>
function whichIsChecked(){
var selected = "";
var elements = document.getElementsByName("colors[]");
for(var i=0; i<=elements.length; i++){
if(elements[i].checked){
//alert(elements[i].value) // values are displayed
selected += elements[i].value + "\n";
}
}
alert(selected); // not storing
}
</script>
<form method="post" action="">
<input type="checkbox" name="colors[]" value="red">
<input type="checkbox" name="colors[]" value="blue">
<input type="checkbox" name="colors[]" value="green">
<input type="button" name="submit" value="Submit" onclick="whichIsChecked()">
</form>
Your for
loop is going too far and causing a TypeError because elements[3] doesn't exist. Change <=
to be <
.
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.