簡體   English   中英

如何在多復選框 onchange 事件中獲取復選框值

[英]How to get checkbox value in multicheckbox onchange event

我在 woocommerce 結帳頁面上創建了兩個自定義字段。 第一個字段是文本,第二個是多復選框。 我希望這兩個字段都使用 Onchange 事件在同一頁面上顯示 output 。

文本字段代碼是

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

我想像文本字段一樣顯示復選框的文本。 因此,當任何復選框被選中時,它的值應該出現,如果用戶取消選中它,它的文本也應該消失。

我有辦法 go 關於這個,假設我們有這兩個輸入復選框按鈕。 首先,您必須使用 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;
}

我希望這對你有用:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM