首页 > 解决方案 > 如何在多复选框 onchange 事件中获取复选框值

问题描述

我在 woocommerce 结帐页面上创建了两个自定义字段。第一个字段是文本,第二个是多复选框。我希望两个字段都使用 Onchange 事件在同一页面上显示输出。

文本字段代码是

<p class="form-row form-row-wide wooccm-field wooccm-field-wooccm11 wooccm-type-text validate-required woocommerce-validated" id="billing_wooccm11_field" data-priority="50">
    <label for="billing_wooccm11" class="">Other NAME&nbsp;<abbr class="required" title="required">*</abbr></label>
    <span class="woocommerce-input-wrapper">
        <input type="text" class="input-text wooccm-required-field" name="billing_wooccm11" id="billing_wooccm11" placeholder="" value="" data-required="1">
    </span>
</p>

我已使用此代码显示文本字段的值

<script>

document.getElementById("billing_wooccm11").onchange = function() {myFunction()};

function myFunction() {
var input = document.getElementById("billing_wooccm11").value;

document.getElementById("demo").innerHTML = input;
}
</script>

    <p id="demo"></p>

它正在工作并根据需要显示价值。但是第二个多复选框字段不起作用

多复选框字段代码是

<p class="form-row form-row-wide wooccm-field wooccm-field-wooccm14 wooccm-type-multicheckbox validate-required" id="billing_wooccm14_field" data-priority="130">
    <label for="billing_wooccm14" class="">PROGRAMME&nbsp;<abbr class="required" title="required">*</abbr></label>
    <span class="woocommerce-input-wrapper"> 
        <span class="woocommerce-multicheckbox-wrapper" data-required="1">
            <label><input type="checkbox" name="billing_wooccm14[]" value="one"> One</label>
            <label><input type="checkbox" name="billing_wooccm14[]" value="two"> Two</label>
            <label><input type="checkbox" name="billing_wooccm14[]" value="three"> Thress</label>
            <label><input type="checkbox" name="billing_wooccm14[]" value="Four"> four</label>
        </span>
    </span>
</p>

我想像文本字段一样显示复选框的文本。因此,当任何复选框被选中时,它的值应该出现,如果用户取消选中它,它的文本也应该消失。

标签: javascriptphpwordpresswoocommerceonchange

解决方案


我有办法解决这个问题,假设我们有这两个输入复选框按钮。首先,您必须使用 name 属性遍历您拥有的按钮。

<input type="checkbox" class="myinput" name="input_check" value="one">
<input type="checkbox" class="myinput" name="input_check" value="two">

然后对于js代码:

document.querySelector('[name="input_check"]').onchange = function() {myFunction()};
function myFunction(){
var checkbox = document.querySelectorAll('.myinput');
for(let i=0; i<checkbox.length; i++)
  if (checkbox[i].checked)
      document.getElementById('demo').innerHtml = checkbox[i].value;
}

我希望这对你有用:)


推荐阅读