-1

I'm writing a function that is supposed to loop through all my checkboxes and load the "value" of the checkboxes that are checked into an array, however nothing is executing beyond the first for loop. I'm completely stumped here, what am I missing?

function saveSettings(){
    var count = 1; //count for db
    var checked=[]; //array of checked values
    var inc = 0; //only incremented when checkbox is checked
    var dataString = "x";

    for(var i=0; i<=2; i++) { //loads checked array with checked values
        if(document.getElementById("check"+i).checked == true){
            checked[inc] = document.getElementById("check"+i).value;
            alert(checked[inc]) // <------ executing as expected
            inc++;
        }
    }

    alert("made it") // <------ not executing
    if(checked.length>0){ // loads checked values into dataString
        for(var i=0; i == checked.length; i++){
            if(i == 0){
                dataString = "co_" + count +"="+checked[i]
            }
            else {
                dataString = dataString +"&co_" + count +"="+checked[i]
            }
            count++;
        }
    }

    alert(dataString)
fuyushimoya
  • 9,715
  • 3
  • 27
  • 34
batman
  • 13
  • 1
  • how many checkboxes are there... any error in your browser console – Arun P Johny Aug 06 '15 at 03:19
  • Can you create jsfiddle ? – CMPS Aug 06 '15 at 03:20
  • Or at least post your html code – VMcreator Aug 06 '15 at 03:21
  • One issue to be aware of is scoping. You are using var i=0 TWICE. 'i' already exists by the time it makes it to the second loop. – dannypaz Aug 06 '15 at 03:22
  • @livepo but the scopes are different. If he was using i =0; without the 'var' declaration, there would be a problem. – lockedz Aug 06 '15 at 03:23
  • make your first loop condition : i<2 – VMcreator Aug 06 '15 at 03:23
  • Also, instead of using alert, you should use console.log. Browsers will block multiple alerts after a certain number. – dannypaz Aug 06 '15 at 03:24
  • @batman, why the i<=2 in the for? Could you provide your HTML too? – lockedz Aug 06 '15 at 03:24
  • 3
    http://jsfiddle.net/arunpjohny/531kjvd8/2/ - looks fine – Arun P Johny Aug 06 '15 at 03:24
  • The second for loop should be `for (var i = 0; i < checked.length; i++) {` – Arun P Johny Aug 06 '15 at 03:24
  • 1
    @lockedz you should use 'let' instead of 'var' in that case. See: http://stackoverflow.com/questions/762011/javascript-let-keyword-vs-var-keyword – dannypaz Aug 06 '15 at 03:24
  • 1
    it works fine though, check the fiddle. – VMcreator Aug 06 '15 at 03:25
  • Do you have 3 checkboxes with id `check0`, `check1` and `check2` or just 2 – Arun P Johny Aug 06 '15 at 03:25
  • http://jsfiddle.net/arunpjohny/531kjvd8/3/ – Arun P Johny Aug 06 '15 at 03:29
  • @livepo oh, that makes sense. Thanks, mate. – lockedz Aug 06 '15 at 03:30
  • I checked the fiddle @ArunPJohny created. Looks like it's working there. I tried testing on chrome and ie and it is still not getting past that for loop? There are currently only 2 checkboxes but that number is dynamic could be 2 could be 100. I plan to replace the 2 with something like "checkbox.length" variable. Just put the 2 for testing purposes. – batman Aug 06 '15 at 03:32
  • @livepo `let` is a bit too new… it requires this weird version opt-in to JavaScript 1.7 or above in Firefox… I wouldn’t recommend it now. – Sebastian Simon Aug 06 '15 at 03:32
  • This question is answerable by debugging the code with [debugging tools](http://webmasters.stackexchange.com/q/8525) available in your browser. Watch out for _errors_. [Rubber Duck Debug](http://rubberduckdebugging.com) your code. If you are not sure what your code does, use [`console.log`](https://developer.mozilla.org/en/docs/Web/API/Console/log) or [`debugger`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/debugger). Make sure your code is _valid_ with tools like [JSHint](http://jshint.com). Only _then_, ask a question on StackOverflow and _show your research_. – Sebastian Simon Aug 06 '15 at 03:33
  • can you add a common class to all the checkboxex – Arun P Johny Aug 06 '15 at 03:34
  • or do you want to consider all the checkboxes in the page – Arun P Johny Aug 06 '15 at 03:34
  • @batman see http://jsfiddle.net/arunpjohny/531kjvd8/5/ – Arun P Johny Aug 06 '15 at 03:36
  • @Xufox I think modern browsers allow it if you 'use strict'; Also, I found this question under nodejs. Thanks for clarifying. – dannypaz Aug 06 '15 at 03:42
  • @ArunPJohny I added a common class to all the checkboxes, your last fiddle help immensely, and it is all working now thanks! – batman Aug 06 '15 at 03:50
  • @batman I've added it as an answer below – Arun P Johny Aug 06 '15 at 03:51

4 Answers4

0

in this line

if(document.getElementById("check"+i).checked == true){ //...

the getElementById will return an undefined value, and undefined does not have the .checked property.

how many checkboxes do you have in the document?

Sombriks
  • 3,370
  • 4
  • 34
  • 54
0

Try below working solution. Second for loop condition in your code (i == checked.length) is wrong. It should be i < checked.length)

function saveSettings() {

        var count = 1; //count for db
        var checked = []; //array of checked values
        var inc = 0; //only incremented when checkbox is checked
        var dataString = "x";

        for (var i = 0; i <= 2; i++) { //loads checked array with checked values
            if (document.getElementById("check" + i).checked == true) {
                checked[inc] = document.getElementById("check" + i).value;
                inc++;
            }
        }
        if (checked.length > 0) { // loads checked values into dataString
            for (var i = 0; i < checked.length; i++) {
                if (i == 0) {
                    dataString = "co_" + count + "=" + checked[i]
                }
                else {
                    dataString = dataString + "&co_" + count + "=" + checked[i]
                }
                count++;
            }
        }
        alert(dataString)
    }
0

your second for loop had a mistake

function saveSettings(){
    var count = 1; //count for db
    var checked=[]; //array of checked values
    var inc = 0; //only incremented when checkbox is checked
    var dataString = "x";

    for(var i=0; i<=2; i++) { //loads checked array with checked values
        if(document.getElementById("check"+i).checked == true){
            checked[inc] = document.getElementById("check"+i).value;
            alert(checked[inc]) // <------ executing as expected
            inc++;
        }
    }

    alert("made it") // <------ not executing
    if(checked.length>0){ // loads checked values into dataString
        for(var i=0; i < checked.length; i++){
            if(i === 0){
                dataString = "co_" + count +"="+checked[i]
            }
            else {
                dataString = dataString +"&co_" + count +"="+checked[i]
            }
            count++;
        }
    }

    alert(dataString)
    }
<input type="checkbox" id="check0"/>
<input type="checkbox" id="check1"/>
<input type="checkbox" id="check2"/>
<button onclick="saveSettings()">Run</button>
Justin Poehnelt
  • 2,992
  • 1
  • 19
  • 23
0

From your description of the problem, I think the problem is the number of checkboxes, if you have only 2 checkboxes then the condition i<=2 will cause problem because docuement.getElementById('check2') will be undefined causing an error like Uncaught TypeError: Cannot read property 'checked' of null in your console.

Since you are trying to deal with dynamic number of elements try to use a class to select the checkboxs of interest like

function saveSettings() {

  var checked = [];
  var dataString = "x";

  var checks = document.getElementsByClassName('check');
  //if you can't add a class then fetch all the checkboxes in the page
  //var checks = document.querySelectorAll('input[type="checkbox"]');

  for (var i = 0; i < checks.length; i++) {
    if (checks[i].checked == true) {
      checked.push(checks[i].value);
    }
  }
  console.log("made it: ", checked)

  if (checked.length > 0) {
    dataString = '';
    for (var i = 0; i < checked.length; i++) {
      dataString += (i == 0 ? '' : '&') + "co_" + i + "=" + checked[i]
    }
  }
  alert(dataString)
}
<input type="checkbox" class="check" id="check0" value="1" />
<input type="checkbox" class="check" id="check1" value="2" />
<input type="checkbox" class="check" id="check2" value="3" />
<br />
<button onclick="saveSettings()">Test</button>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531