javascript - 更改单选按钮输入选择未按预期工作,无法弄清楚
问题描述
我想弄清楚我的方法出了什么问题。我有两个复选框选项(单选),如果单击一个,则某些输入必须更改为必填字段,如果单击第二个,则选项 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 提供的所有可用解决方案,但没有奏效。先感谢您。
解决方案
单击单选按钮只会触发该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>
推荐阅读
- forms - Vue.js - ref 属性自动从输入中删除
- node.js - 如何使用 NodeJS 和 PM2 对 MongoDB 进行身份验证以不断运行 Node
- javascript - 如何获取响应标头 - 获取响应标头的问题
- sql - 提高 postgresql 上时间戳范围的连接速度
- twitter-bootstrap - 关于引导阴影的问题,使用阴影类没有任何反应
- android - 如何在改造中使用原始 json 对象调用改造 @DELETE 方法?
- vue.js - 在 nativescript-vue 视图模式组件中显示数组数据
- asp.net-core - ASP.NET Core 3 Blazor:在服务器的本地主机上运行正常,但在服务器外部运行错误:WebSocket 握手期间出错:意外响应代码:200
- ejabberd - ejabberd 19.05 不适用于 mod_log_chat
- java - 使用 Jsoup 登录的 Java 抓取网站