2

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>

1 Answer 1

3

Your for loop is going too far and causing a TypeError because elements[3] doesn't exist. Change <= to be <.

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

2 Comments

+1. @karthik_spain the first step in debugging is always to check the error that your code is giving you – in this case open developer tools in Chrome or Firebug in Firefox and you'll see this error.
@CharlieS i am already using webdeveloper tool in firefox, which gave me TypeError. Wonder if error message would have been more meaningful like "out of range" or something similar to it.

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.