【问题标题】:Changing Radio button input selection is not working as expected, unable to figure it out更改单选按钮输入选择未按预期工作,无法弄清楚
【发布时间】:2018-08-15 17:54:14
【问题描述】:

我很难弄清楚我的方法有什么问题。 我有两个复选框选项(单选),如果单击一个,则输入一些 必须更改为必填字段,如果单击第二个,则选项 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 提供的所有可用解决方案,但没有奏效。提前谢谢你。

【问题讨论】:

  • 我有两个复选框选项(收音机)?!! checkboxradio
  • 收音机。对此感到抱歉。

标签: javascript ruby-on-rails radio-button forms


【解决方案1】:

单击单选按钮只会触发该按钮上的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>

【讨论】:

  • 轰隆隆!非常感谢。终于!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2019-12-31
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
相关资源
最近更新 更多