0

Can't get loop to spit out a string of the values in checked checkboxes.

Basic Javascript.

I've tried to follow various other stackoverflow posts to no avail. This and This seemed to be what was closest to what I'm trying to make work.

The HTML is just a row of

<div class="help-days">MON<br><input type="checkbox" id="d0-field" value="Monday" aria-describedby="avail-help"></div>

I've tried

var element = document.getElementsByClassName('help-days');
for (var i = 0; i <= 6; i++) {
    if (element[i].checked) {
        var day = $('#d' + i + '-field').val();
        days = days + ' ' + day;
    }
}

and

for (var i = 0; i <= 6; i++) {
    var element = document.getElementById('#d' + i + '-field')
    if (element[i].checked) {
        var day = $('#d' + i + '-field').val();
        days = days + ' ' + day;
    }
}

Below example outputs Monday Tuesday Wednesday Thursday Friday Saturday Sunday which leads me to believe there's something about using HTMLCollection and for loops & checking checkboxes that I'm not quite grasping?

for (var i = 0; i <= 6; i++) {
    var day = $('#d' + i + '-field').val();
    if (day) {
        days = days + ' ' + day;
    }
}

I'm trying to create a string that appends a checkbox 'value' to the string, if the checkbox is checked.

Any help appreciated!

Lindenkron
  • 13
  • 4

2 Answers2

0

No need to include the # character when you use document.getElementById. The # character is used with JQuery

And you don't need to write element[i].checked, only element.checked because element is already a reference to your checkbox element.

for (var i = 0; i < 6; i++) {
  var element = document.getElementById('d' + i + '-field')

  if (element.checked) {
    var day = element.value
    days += ' ' + day;
  }
}
Saraband
  • 1,540
  • 10
  • 18
  • After missing around with it a bit more, I got it to work. My original method with ID was fine, the # broke everything from what I can tell though. Thanks for the hint. – Lindenkron Jan 22 '19 at 17:01
0

document.getElementsByClassName('help-days'); this will return the list of divs, and they don't have a checked property, you'll need to select the checkboxes inside of them :

for (var i = 0; i < 2; i++) {
    var checkbox = element[i].childNodes[2];

    if (checkbox.checked) {
        var day = $('#d' + i + '-field').val();
        days = days + ' ' + day;
    }
}

var days = '';

for (var i = 0; i < 3; i++) {
  var element = document.getElementById('d' + i + '-field')

  if (element.checked) {
    var day = element.value
    days += ' ' + day;
  }
}

console.log(days)
<div class="help-days">MON<br><input type="checkbox" id="d0-field" value="Monday" aria-describedby="avail-help" checked></div>
<div class="help-days">TUE<br><input type="checkbox" id="d1-field" value="Tuesday" aria-describedby="avail-help" checked></div>
<div class="help-days">WED<br><input type="checkbox" id="d2-field" value="Wednesday" aria-describedby="avail-help"></div>
Taki
  • 17,320
  • 4
  • 26
  • 47