【问题标题】:How to make a function in Vanilla JS that puts checked attribute to the radio inputs before the selected input?如何在 Vanilla JS 中创建一个函数,在选定输入之前将选中的属性放入无线电输入?
【发布时间】:2020-06-02 17:42:49
【问题描述】:

我找不到这个的解决方案。

需要使用 JavaScript 对所选输入之前的输入和未选中的输入进行属性检查。

UPD:将输入类型更改为“复选框”,现在我需要一个函数,在最后一个选中的复选框之前标记“选中”复选框,同时取消选中后续框以防它们之前被选中。

注意:解决方案必须使用与 ES5 兼容的语法。

请提供代码示例!

<input type="checkbox" id="product-1" name="toggle">
<input type="checkbox" id="product-2" name="toggle">
<input type="checkbox" id="product-3" name="toggle">
<input type="checkbox" id="product-4" name="toggle">
<input type="checkbox" id="product-5" name="toggle">

【问题讨论】:

  • 这不是收音机的用途。你不是说复选框吗?单选按钮仅用于单选。
  • 没有确认,但我几乎可以肯定它正在检查其他单选按钮,但是一旦您随后检查他们的以下同级按钮,它们就会被取消选中。
  • 我想我可以改变他们的默认行为,并让它发挥作用。
  • 不。听起来像是不好的做法。如果您不喜欢方形样式的复选框,最好尝试自定义它们的外观,而不是尝试自定义单选按钮行为。顺便说一句,你的照片很好。
  • 谢谢,它是一个 Slint 吉他手)这不是关于复选框的风格,而是关于行为。我已经更新了问题。

标签: javascript arrays checkbox ecmascript-5 preventdefault


【解决方案1】:

那么,朋友,可以这么简单:

// checkbox elements
var boxes = document.getElementsByName('toggle');

// function to bind to each of the input tags' change event
function markPreceding() {

  // retrieve the value from the clicked input
  var curIndex = this.value;

  // iterate through every single checkbox named toggle
  for (var i = 0, box = boxes[i]; i < boxes.length; box = boxes[++i]) {
    // if data-index is lower or equal to curIndex, then true; else, false
    box.checked = box.value <= curIndex;
  }

}

// add function to the onchange handler of each input
for (var i = 0, box = boxes[i]; i < boxes.length; box = boxes[++i]) {
  box.onchange = markPreceding;
}
<input type="checkbox" id="product-1" name="toggle" value="1">
<input type="checkbox" id="product-2" name="toggle" value="2">
<input type="checkbox" id="product-3" name="toggle" value="3">
<input type="checkbox" id="product-4" name="toggle" value="4">
<input type="checkbox" id="product-5" name="toggle" value="5">

注意事项

我使用data attributes 存储了每个复选框的索引。

例如,我可以使用value 属性。我更喜欢使用数据属性,因为您可能想将value 用于其他用途。这是你的电话。见帖子底部

我们可以使用 .dataset.index 从 JavaScript 中的 HTML 视图中检索每个属性 data-index。它可能是任何其他名称而不是“索引”。请记住,如果您使用多个单词,例如 HTML 中的 data-my-custom-prop,您必须在 JS 中将其称为 .dataset.myCustomProp(它们采用驼峰式命名)。

.checked 属性无论如何都会存储一个布尔值,因此您可以通过比较 box.dataset.index &lt;= curIndex 将评估为 truefalse,尊重地选中或取消选中该框。

编辑: 既然您在 cmets 中询问,我尝试将其转换为 ES5 兼容语法。一方面,我停止使用数据属性,并使用 this 关键字而不是 event.target 检索输入值(也许我不需要更改它,但我得到的印象是在天)。

【讨论】:

  • 非常感谢,先生!正是我需要的!
  • 我遇到了一个问题,我没有在我的项目中使用 Babel,我不能在这个项目中使用它。你能告诉我如何在 ES5 语法中使用它吗?
  • 我编辑了我的答案。请检查这是否适合您! :)
【解决方案2】:

&lt;input type="radio"&gt; 的默认行为是只允许选择一个输入/选项。因此,只有最后一个输入被标记为您的 JS 代码。 要能够选择多个选项,请使用&lt;input type="checkbox"&gt;。 更多参考:MDN Docs.

【讨论】:

  • 您好!但是我想设置一个步进进度条,如何用JS实现,代码示例会很方便,提前谢谢
猜你喜欢
  • 2019-11-11
  • 1970-01-01
  • 2020-02-10
  • 2015-12-20
  • 2022-07-30
  • 2021-11-07
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多