disable input on check checkbox

2019-06-28 08:12发布

Need to disable an input when the check-box is unchecked, and when it is checked enable it.

My code is like this:

<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="select" name="x" class="mySelect" />
</div>

<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="select" name="x" class="mySelect" />
</div>

<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="select" name="x" class="mySelect" />
</div>

But I want to disable and enable the select input which correspond to a check-box. If user clicks in first check box enable first input, and do the same for second and third.

2条回答
不美不萌又怎样
2楼-- · 2019-06-28 08:53

If you want to go the pure CSS route, you can write CSS that changes the opacity and pointer-events when the checkbox sibling is unchecked.

.y .myCheck:not(:checked) + .mySelect {
  pointer-events: none;
  opacity: 0.6;
}
<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="text" tabindex="-1" name="x" class="mySelect" />
</div>

<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="text" tabindex="-1" name="x" class="mySelect" />
</div>

<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="text" tabindex="-1" name="x" class="mySelect" />
</div>

Tab Issue

In order to stop someone from tabbing into the input, you can add tabindex="-1" to the input.

查看更多
做个烂人
3楼-- · 2019-06-28 08:55

One simple solution:

$(".mySelect").prop("disabled", true);

$("input:checkbox").on("change", function () {
    $(this).next().prop("disabled", !$(this).prop("checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="select" name="x" class="mySelect" />
</div>
<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="select" name="x" class="mySelect" />
</div>
<div class="y">
    <input type="checkbox" class="myCheck" />
    <input type="select" name="x" class="mySelect" />
</div>

References

.next()

.prop()

查看更多
登录 后发表回答