英文:
Checkboxes read-only attribute HTML
问题
我正在开发一个网站,我需要一个特定的复选框,当它未选中时,相关的输入框会具有"readonly"属性,当我选中它时,输入框的"readonly"属性会被移除。目前的情况是,我加载网站时,复选框未选中,输入框没有"readonly"属性,正如它本应该有的那样。然而,当我选中和取消选中它时,输入框会获得"readonly"属性。
以下是Javascript代码:
const checkbox = document.getElementById("check_pt");
const inputElement = document.getElementById("pi_pt");
checkbox.addEventListener("change", function() {
if (!checkbox.checked) {
inputElement.setAttribute("readonly", "true");
} else {
inputElement.removeAttribute("readonly");
}
});
如果你需要更多帮助,请随时提问。
英文:
I am developing a website, and I need a certain checkbox that when is unchecked the correspondent input box has the read-only attribute and when I check it the read-only attribute gets removed from the input box. Right now, what happens is I load the website, the checkbox is unchecked and the input box does not has the read-only attribute as it was supposed to. Altough when I check and uncheck it the input box gets the read-only attribute.
Why is this happening?
Here is the Javascript code:
const checkbox = document.getElementById("check_pt");
const inputElement = document.getElementById("pi_pt");
checkbox.addEventListener("change", function() {
if (!(checkbox.checked)) {
inputElement.setAttribute("readonly", "true");
} else {
inputElement.removeAttribute("readonly");
}
});
答案1
得分: 1
设置函数会在复选框更改时设置readonly
属性。当文档最初加载时,不会设置它,因为用户还没有更改它。如果你希望函数在文档最初加载时运行,那么你需要在那个时候调用它。或者,你可以在HTML中设置属性,而不是在JS中修改它(通常在设置属性的默认值时更合理)。请注意,如果你执行其中任何一种操作,状态将永远不会更改,因此更改事件处理程序将永远不会运行。
英文:
Your function sets the readonly
attribute when the checkbox is changed.
It doesn't get set when the document initially loads, because the user hasn't changed it.
If you want the function to run when the document initially loads, then you'll need to call it at that time. Alternatively, you could set the attribute in the HTML instead of modifying it with JS (which generally makes more sense when setting default values for attributes). Note that if you do either of these, then the state can never change so the change event handler will never run.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论