JS数组旁边的复选框

时间:2017-03-15 23:38:35

标签: javascript arrays

我有一个从数组中打印列表的函数。我希望用户能够使用旁边的复选框选择阵列中的多个不同项目。如何在每个数组元素旁边显示一个复选框? (目前正在学习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;
}

3 个答案:

答案 0 :(得分:2)

&#13;
&#13;
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);
&#13;
<form>
<div id="myDiv"></div>
<input type="submit"/>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

复选框名称应该相同。因此,在提交表单时,您可以将其作为服务器端的数组读取

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>

答案 2 :(得分:0)

您的for循环写入复选框标记中刚刚丢失的代码:

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

正如你所说,你正在学习JavaScript,我邀请你接受在JS中做事的功能风格:

&#13;
&#13;
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();
&#13;
<div id="demo"></div>
&#13;
&#13;
&#13;