简体   繁体   English

单击关闭按钮时,取消选中单选按钮

[英]Uncheck radio buttons when the close button is clicked

I'm currently have a modal with some radio buttons (".modal-options"), and a close modal button. 我目前有一个带有一些单选按钮的模态(“ .modal-options”)和一个关闭的模态按钮。 Im trying to make it so when the close button is clicked, all the clicked radio buttons become unchecked. 我试图做到这一点,因此当单击关闭按钮时,所有单击的单选按钮都变为未选中状态。 current code is below. 当前代码如下。 Console is saying that removeAttr is not a function...? 控制台说removeAttr不是函数...? thanks 谢谢

  <p class='information'> Cancel Appointment? </p> <div class="modal-flex"> <%= f.radio_button :delete_appointment, :true %> <%= f.label :delete_appointment_true, "Yes", class: "modal-options cancel" %> <%= f.radio_button :delete_appointment, :false %> <%= f.label :delete_appointment_false, "No", class: "modal-options cancel" %> </div> 

  <p class="close"> <%= t(".close") %> </p> 

 var close = document.querySelector(".close"); var buttons = document.querySelectorAll(".modal-options"); close.addEventListener("click", (event) => { buttons.forEach(function(button) { button.removeAttr('checked'); }); }) 

Firstly, removeAttr isn't a function on HTML Elements; 首先, removeAttr不是HTML元素上的函数; you meant removeAttribute ( mdn ). 您的意思是removeAttributemdn )。

Secondly, for unchecking an input, you'd want input.checked = false instead. 其次,要取消选中输入,您需要输入input.checked = false The reason removeAttribute doesn't work is because if you inspect the input element, you will see that no 'checked' attribute is being added or removed when toggling. removeAttribute不起作用的原因是,如果您检查输入元素,则在切换时将看到没有添加或删除“ checked”属性。 'Checked' is a property, not an attribute; “已检查”是属性,不是属性; the distinction is important in this case and when getting into custom elements. 在这种情况下以及进入自定义元素时,区别很重要。

  document.querySelector('button').addEventListener('click', () => { document.querySelector('input').checked = false; }); 
 <input type="checkbox"> <button>uncheck</button> 

.removeAttr() is jQuery method. .removeAttr()是jQuery方法。 The equivalent JavaScript method is remove​Attribute() 等效的JavaScript方法是remove​Attribute()

Though, I prefer using the checked property: 虽然,我更喜欢使用checked属性:

button.checked = false;

You are targeting the label, instead you should target the radio button: 您要定位标签,而应该定位单选按钮:

var buttons = document.querySelectorAll(".modal-flex input[type=radio]");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM