【问题标题】:Get all cheched ckexbox and set it to hiden input获取所有选中的复选框并将其设置为隐藏输入
【发布时间】:2021-04-19 05:29:47
【问题描述】:

我有 5 个 html 复选框,但每次它们具有不同的值时,我希望每次选中或取消选中复选框时调用此 js 函数以获取所有选中的复选框并将其添加到隐藏输入中

这是我的html

<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="1" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="2" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="3" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="4" onchange="getValue(this.value)">
<input type="checkbox" id="checkbox" class="checkbox" name="checkbox" value="5" onchange="getValue(this.value)">
<input type="hidden" id="ticketsPay" name="ticketsPay" value="">

这是我的 js

let myArray = (function() {
      let a = [];
      $(".checkboxes:checked").each(function() {
          a.push(this.value);
      });
      return a;
  })()

  document.getElementById('ticketsPay').value = myArray.toString();

JS不要在隐藏输入中保存所有选中的复选框有什么想法吗?

【问题讨论】:

  • (Offtopic):不要使用内联 JS on* 处理程序,就像你不使用内联 style 属性一样。 CSS 和 JS 应该只在一个地方,那就是它们各自的文件或标签。
  • 回归基础:ID 应该是唯一的!
  • 您正在查询.checkboxes,而您的复选框属于.checkbox。不要将语法与代码混淆!

标签: javascript html checkbox


【解决方案1】:

这是一个使用 Array.prototype.reduce 并仅计算 checked 的示例:

const EL_inp = document.querySelector("#ticketsPay");
const ELs_ckb = document.querySelectorAll('[name="checkbox"]');

const setChecked = () => {
  EL_inp.value = [...ELs_ckb].reduce((a, EL) => {
    if (EL.checked) a.push(EL.value);
    return a;
  }, []);
};

ELs_ckb.forEach(EL => EL.addEventListener("input", setChecked));
<input type="checkbox" class="checkbox" name="checkbox" value="1">
<input type="checkbox" class="checkbox" name="checkbox" value="2">
<input type="checkbox" class="checkbox" name="checkbox" value="3">
<input type="checkbox" class="checkbox" name="checkbox" value="4">
<input type="checkbox" class="checkbox" name="checkbox" value="5">
<input id="ticketsPay" name="ticketsPay" value="" readonly>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多