0

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;
}
1
  • 2
    text += "<input type='checkbox' data-index='" + i + "'/>" + courses[i] + "<br>";! The data-index attribute will have the index of the item from the array! Commented Mar 15, 2017 at 23:43

3 Answers 3

2

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>

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

Comments

0

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>

Comments

0

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>

Comments

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.