javascript - 如何在多复选框 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 <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 <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>
我想像文本字段一样显示复选框的文本。因此,当任何复选框被选中时,它的值应该出现,如果用户取消选中它,它的文本也应该消失。
解决方案
我有办法解决这个问题,假设我们有这两个输入复选框按钮。首先,您必须使用 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;
}
我希望这对你有用:)
推荐阅读
- excel - MS Excel 根据其他列填充列
- pandas - 在 dask 数据帧中使用 map_partitions 获取目录名称
- reactjs - 在 IIS 中访问另一个路由返回错误
- python - 我在哪里为 Qt 设计器的单个提升 QWidget 编写类
- python - F0321 01:22:08.021044 18633 math_functions.cpp:250] 检查失败:a <= b (0 vs. -1.19209e-07)
- typescript - 从扩展 Typegoose 并包含静态类型特定方法的父类继承
- amazon-web-services - 重新创建 EMR 集群后保持 HDFS 状态
- javascript - AngularJS ng-repeat 不适用于选择选项
- r - 如何确定向量中有多少元素包含来自第二个向量的模式?
- javascript - 使用 Javascript 拦截开发服务器上的链接