【问题标题】:Add checkbox value to another hidden input field if first hidden field has content如果第一个隐藏字段有内容,则将复选框值添加到另一个隐藏输入字段
【发布时间】:2013-04-18 01:02:12
【问题描述】:

我有一组 4 个复选框。

当任何两个被选中时,它们的值就会被复制到两个隐藏的输入字段中。

第一个选中的复选框值转到第一个输入id="checkedBox1"

如何让第二个选中的复选框值转到第二个隐藏输入字段id="checkedBox2"

我已使用下面的 JavaScript 函数将值放入各个复选框的每个输入中,但无法弄清楚如何遍历所有四个复选框的列表并将两个选中的复选框放入每个单独的输入字段中。

复选框:

<input type="checkbox" value="test1" id="a" name="one"><label>Test11</label>
<input type="checkbox" value="test2" id="b" name="one"><label>Test12</label>
<input type="checkbox" value="test3" id="c" name="one"><label>Test13</label>
<input type="checkbox" value="test4" id="d" name="one"><label>Test14</label>

  <input type="hidden" value="" id="checkedBox1">
  <input type="hidden" value="" id="checkedBox2">

<script>
function populate() {
  var checkboxes = document.getElementsByName('one');
  var ip1 = document.getElementById('checkedBox1');
  var ip2 = document.getElementById('checkedBox2');

  // clear current values
  ip1.value = ip2.value = '';

  var first = false;
  var second = false;

  // Loop over checkboxes,stop when found 2 that are checked
  for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {

  if (checkboxes[i].checked) {

  if (!first) {
    ip1.value = checkboxes[i].value;
    first = true;

  } else if (!second) {
    ip2.value = checkboxes[i].value;
    second = true;
  }
  }
  }
  }

 $('input[type="checkbox"]').on('change', function() {
 populate();
 }).change();
 </script>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    你可以尝试普通的 JS,虽然我会使用表单属性访问而不是 getElementsByNamegetElementById

    function populate() {
      var checkboxes = document.getElementsByName('one');
      var ip1 = document.getElementById('checkedBox1');
      var ip2 = document.getElementById('checkedBox2');
    
      // clear current values
      ip1.value = ip2.value = '';
    
      var first = false;
      var second = false;
    
      // Loop over checkboxes,stop when found 2 that are checked
      for (var i=0,iLen=checkboxes.length; i<iLen || !(first && second); i++) {
    
        if (checkboxes[i].checked) {
    
          if (!first) {
            ip1.value = checkboxes[i].value;
            first = true;
    
          } else if (!second) {
            ip2.value = checkboxes[i].value;
            second = true;
          }
        }
      }
    }
    

    编辑

    感谢 Mal,每次都添加了一行来清除隐藏输入的值。

    【讨论】:

    • 如果您一开始就选中复选框,这将非常有用。如果您在不刷新页面的情况下取消选中并重新检查新值,则会将 firstsecond 混淆。
    • 感谢 Rob 和 Mal 提供的帮助。根据上面编辑的 OP 代码,我刚刚能够在我的实时版本中使用它。完美运行。再次感谢。
    猜你喜欢
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多