英文:
making a checkbox readonly on a condition in javascript
问题
我网页上有以下代码。当选中复选框#1时,我希望复选框#3是只读的。如果没有选中#1复选框,我希望#3复选框是可用的,而不是只读的。
<div class="form-group row">
<div class="col">
1.
<input id="Notengaged"
asp-for="@Model.Sec3EmployedOutside"
type="checkbox"
onclick='handleClick(this);'
/>
I am not employed
</div>
</div>
<div class="form-group row">
<div class="col">
3.
<input id="engaged"
asp-for="@Model.Sec3EmployedOutside"
type="checkbox"
/>
I am employed
</div>
</div>
为了实现这个目标,我编写了以下代码,但似乎不起作用。无论我是否点击#1复选框,#3复选框都始终是启用的。
function handleClick(cb)
{
if (cb.checked == true)
{
document.getElementById('engaged').readOnly = true;
}
alert("Clicked, new value = " + cb.checked);
}
英文:
I have the following code on my page. When # 1 check box is checked, I want the #3 checkbox to be readonly. If #1 check box is not checked then, I want the #3 check box to be enabled or not to be readonly.
<div class="form-group row">
<div class="col">
1.
<input id="Notengaged"
asp-for="@Model.Sec3EmployedOutside"
type="checkbox"
onclick='handleClick(this);'
/>
I am not employed
</div>
</div>
<div class="form-group row">
<div class="col">
3.
<input id="engaged"
asp-for="@Model.Sec3EmployedOutside"
type="checkbox"
/>
I am employed
</div>
</div>
In order to accomplish this, I wrote the following code, but this does not seem to work. the #3 checkbox
is always enabled no matter if I click #1 checkbox
or not.
function handleClick(cb)
{
if (cb.checked == true)
{
document.getElementById('engaged').readOnly = true;
}
alert("Clicked, new value = " + cb.checked);
}
答案1
得分: 2
根据这个链接所述,readonly
不适用于复选框。相反,应在复选框上使用disabled
。
function handleClick(cb) {
document.getElementById('engaged').disabled = cb.checked;
}
<div class="form-group row">
<div class="col">
1.
<input id="Notengaged" asp-for="@Model.Sec3EmployedOutside" type="checkbox" onclick='handleClick(this);' />
I am not employed
</div>
</div>
<div class="form-group row">
<div class="col">
3.
<input id="engaged" asp-for="@Model.Sec3EmployedOutside" type="checkbox" />
I am employed
</div>
</div>
英文:
As stated at this, readonly
doesn't work on checkboxes. Instead do readonly
on the checkbox, it should be just do disabled
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function handleClick(cb) {
document.getElementById('engaged').disabled = cb.checked;
}
<!-- language: lang-html -->
<div class="form-group row">
<div class="col">
1.
<input id="Notengaged"
asp-for="@Model.Sec3EmployedOutside"
type="checkbox"
onclick='handleClick(this);'
/>
I am not employed
</div>
</div>
<div class="form-group row">
<div class="col">
3.
<input id="engaged"
asp-for="@Model.Sec3EmployedOutside"
type="checkbox"
/>
I am employed
</div>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论