Trenton Tyler
Trenton Tyler

Reputation: 534

Checkbox next to JS array

I have a function that prints a list from an array. I want the user to be able to select multiple different items in the array by using a checkbox next to them. How would I display a checkbox next to each array element? (Currently learning JS)

function par() {
  var courses = ["SDEV", "DBMS","INFM", "CSCI", "SVAD", "NETI", "ITSP", "CSIA"];
  var text = "";
  var i;
  for (i = 0; i < courses.length; i++) {
    text += courses[i] + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}

Upvotes: 0

Views: 56

Answers (3)

Mouneer
Mouneer

Reputation: 13489

function par(domEl) {
  var courses = ["SDEV", "DBMS","INFM", "CSCI", "SVAD", "NETI", "ITSP", "CSIA"];
  var text = "";
  var i;
  for (i = 0; i < courses.length; i++) {
    var checkBox = document.createElement("input");
    checkBox.type = "checkbox";
    checkBox.value = courses[i];
    domEl.appendChild(checkBox);

    var label = document.createElement("label");
    label.innerText = courses[i];
    domEl.appendChild(label);
  }
}

var domEl = document.body.querySelector('#myDiv')
par(domEl);
<form>
<div id="myDiv"></div>
<input type="submit"/>
</form>

Upvotes: 2

ajai Jothi
ajai Jothi

Reputation: 2294

Checkbox names should be same. So that when submitting form you can read that as an array in serverside

function par() {
  var courses = ["SDEV", "DBMS", "INFM", "CSCI", "SVAD", "NETI", "ITSP", "CSIA"];
  document.getElementById("demo").innerHTML = courses.map(function(c){
    return '<label><input type="checkbox" name="courses" value="' + c + '" /> ' + c + '</label>';
  }).join('<br>');
}
par();
<div id="demo"></div>

Upvotes: 0

undko
undko

Reputation: 937

Your just missing code in your for loop to write checkbox markup:

text += '<label><input type="checkbox" value="' + courses[i] + '">' 
  + courses[i] + '</label><br>';

As you said you‘re learning JavaScript I invite you to embrace the functional style of doing stuff in JS:

function par() {
  var courses = ["SDEV", "DBMS","INFM", "CSCI", "SVAD", "NETI", "ITSP", "CSIA"];
  var text = courses.map(function(course) {
    return '<label><input type="checkbox" value="' + course + '">' + course + '</label>';
  }).join('<br>');
  document.getElementById("demo").innerHTML = text;
}
par();
<div id="demo"></div>

Upvotes: 0

Related Questions