【问题标题】:How to get checkbox value in multicheckbox onchange event如何在多复选框 onchange 事件中获取复选框值
【发布时间】:2020-05-22 08:18:07
【问题描述】:

我在 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>

它正在按要求工作并显示价值。但是第二个字段是 multicheckbox 不起作用

多选框字段代码是

<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>

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

【问题讨论】:

  • 解决方案,看起来很简单
  • @Nanoo 是的,这可能很简单,但不幸的是我做不到。
  • 我可以尽快帮助您 - 我确实有答案,但假设 Ess 的答案是合适的。
  • 不,那没有用。如果您有答案,请尽快在此处发布。

标签: javascript php wordpress woocommerce onchange


【解决方案1】:

我有办法解决这个问题,假设我们有这两个输入复选框按钮。首先,您必须使用 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;
}

我希望这对你有用:)

【讨论】:

  • 感谢您的回答,但它对我不起作用。我在input 字段中没有class。我正在使用插件来生成这些字段,所以不能有类或 id。
  • 你可以改用这个名字
  • 用这个 var checkbox = document.querySelectorAll('[name="input_check"]'); 替换它;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
  • 2015-01-31
  • 2018-09-17
  • 2019-08-16
  • 2015-08-09
  • 2016-11-10
  • 1970-01-01
相关资源
最近更新 更多