从数组中获取值并检查(勾选)相关的复选框

时间:2017-01-12 20:39:39

标签: javascript html forms checkbox

我需要你的帮助。

如何从数组中获取值并使用HTML 5的数据属性检查(勾选)相关的复选框?

var x = "[monday,thursday]"

<input name="recurr_weekday" type="checkbox" data-weekday="sunday">
<input name="recurr_weekday" type="checkbox" data-weekday="monday">
<input name="recurr_weekday" type="checkbox" data-weekday="tuesday">
<input name="recurr_weekday" type="checkbox" data-weekday="wednesday">
<input name="recurr_weekday" type="checkbox" data-weekday="thursday">
<input name="recurr_weekday" type="checkbox" data-weekday="friday">
<input name="recurr_weekday" type="checkbox" data-weekday="saturday">

...经过一些处理后,下面的复选框会勾选:

<input name="recurr_weekday" type="checkbox" data-weekday="monday">
<input name="recurr_weekday" type="checkbox" data-weekday="thursday">

3 个答案:

答案 0 :(得分:0)

您可以使用属性选择器

var x = ["monday", "thursday"];

for (let prop of x) {
  document.querySelector("input[type=checkbox][data-weekday=" + prop + "]")
  .checked = true;
}

答案 1 :(得分:0)

您可以使用以下代码:

x.forEach(function (weekDay){
    var htmlElement = document.querySelectorAll('[data-weekday="'+weekDay+'"]').checked = true;
});

它将迭代数组x,每个值我们将找到具有data-weekday value属性的相应元素。

答案 2 :(得分:0)

这是另一个有一些优点的解决方案:

  • 即使同一天有多个复选框,也可以使用,例如,两个复选框data-weekday="monday"
  • 取消选中所选日期数组中的所有recurr_weekday个复选框。
  • 它只查询一次文档,效率更高 - 特别是如果文档很大。

&#13;
&#13;
document.querySelector('button').onclick = checkTheDays;

var myDays = ["monday", "thursday"];

function checkTheDays() {
  var checkboxes = document.querySelectorAll('[name="recurr_weekday"]');

  for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = myDays.indexOf(checkboxes[i].getAttribute('data-weekday')) > -1;
  }
}
&#13;
Week 1:
<input name="recurr_weekday" type="checkbox" data-weekday="sunday">
<input name="recurr_weekday" type="checkbox" data-weekday="monday">
<input name="recurr_weekday" type="checkbox" data-weekday="tuesday">
<input name="recurr_weekday" type="checkbox" data-weekday="wednesday">
<input name="recurr_weekday" type="checkbox" data-weekday="thursday">
<input name="recurr_weekday" type="checkbox" data-weekday="friday">
<input name="recurr_weekday" type="checkbox" data-weekday="saturday">(Initially all unchecked)
<br />Week 2:
<input name="recurr_weekday" type="checkbox" data-weekday="sunday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="monday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="tuesday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="wednesday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="thursday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="friday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="saturday" checked>(Initially all checked)
<br />
<button>
  Check Mondays and Thursdays
</button>
&#13;
&#13;
&#13;