首页 > 解决方案 > 更改单选按钮输入选择未按预期工作,无法弄清楚

问题描述

我想弄清楚我的方法出了什么问题。我有两个复选框选项(单选),如果单击一个,则某些输入必须更改为必填字段,如果单击第二个,则选项 1 的必填字段必须变为不需要。我写了一个脚本,它工作正常。问题:如果我选择第一个复选框(option1),无论我是否更改选择(更改为 option2),都会出现选择 1 的必填字段。他们不会更改为不需要的字段。

脚本:

document.getElementById("pharmacy-nabp-req").addEventListener('change',function(){
document.getElementById("nabp-required").required = this.checked ;
    })

HTML:

    <div class="form-check form-check-inline">
        <%= f.radio_button :submitter_type, 1, checked: false, type: "checkbox", class: "form-check-label", name: "pharmacy-nabp", id: "pharmacy-nabp-req", required: true %>
        <%= label :submitter_type, 'Pharmacy(NABP Required)', class: "form-check-label"%>

    </div>
    <div class="form-check form-check-inline">
        <%= f.radio_button :submitter_type, 2, checked: false, class: "form-check-label", name: "pharmacy-nabp", id: "nabp-notrequired" %>
        <%= label :submitter_type, 'Dispensing Practitioners and Vetenrinarians(NABP Not Required)', class: "form-check-label"%>
    </div>

必填字段 HTML:

<div class="form-group row">
               <%= label :nabp, 'nabp', class: "col-sm-3 form-check-label pt-0"%>
                 <div class="col-sm-9">
                 <div class="form-check form-check-inline">
                   <%= f.text_field :nabp, class: "col-sm-10 form-check-label", id: "nabp-required", name: "nabp-required" %>
                   <abbr class="col-sm-6">(For Pharmacies only)</abbr>
                 </div>
                 </div>
             </div>

道歉,如果这个问题很明显可以回答。我尝试了 SO 提供的所有可用解决方案,但没有奏效。先感谢您。

标签: javascriptruby-on-railsradio-buttonforms

解决方案


单击单选按钮只会触发该change按钮上的事件,而不是单选组中的所有其他按钮。

您应该将事件侦听器添加到组中的所有按钮,并且它应该检查pharmacy-nabp-req按钮是否被选中。

document.getElementsByName("pharmacy-nabp").forEach(function(button) {
  button.addEventListener('change', function() {
    document.getElementById("nabp-required").required = document.getElementById("pharmacy-nabp-req").checked;
  })
});
<input type="radio" name="pharmacy-nabp" id="pharmacy-nabp-req">
<label for="pharmacy-napp-req">Pharmacy(NABP Required)</label>
<input type="radio" name="pharmacy-nabp" id="nap-p-notrequired">
<label for="pharmacy-napp-req">Pharmacy(NABP Not Required)</label>

<div class="form-group row">
  <form>
    <input type="text" id="nabp-required">(For Pharmacies only)
    <input type="submit">
  </form>
</div>


推荐阅读