简体   繁体   English

选中和取消选中复选框上的启用和禁用文本输入

[英]enabled and disabled text input on checkbox checked and unchecked

i've checkbox and text input我有复选框和文本输入

What I need is to enable text input when i check the checkbox and to disable text input when i uncheck the checkbox我需要的是在选中复选框时启用文本输入,并在取消选中复选框时禁用文本输入

I'm using the following code but it do the reverse enable when unchecked / disable when checked so how to adjust it fit with my needs.我正在使用以下代码,但它在未选中时反向启用/选中时禁用,因此如何调整它以满足我的需要。

<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
<script>
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').enabled = this.checked;
};
</script>

any help ~ thanks任何帮助〜谢谢

You just need to add a !您只需要添加一个! in front of this.checked .this.checked前面。

Here's an example that shows the change:这是一个显示更改的示例:

 document.getElementById('yourBox').onchange = function() { document.getElementById('yourText').disabled = !this.checked; };
 <input type="text" id="yourText" disabled /> <input type="checkbox" id="yourBox" />

A jQuery solution could be this one:一个 jQuery 解决方案可能是这样的:

<script>
$('#yourBox').change(function() {
    $('yourText').attr('disabled',!this.checked)
});
</script>

It is the same as Minko's answer but I find it more elegant.它与 Minko 的答案相同,但我觉得它更优雅。

Try it.尝试一下。 If you use a label then add onmousedown to it如果您使用标签,则向其添加 onmousedown

 <form > <input type="text" id="yourText" disabled /> <input type="checkbox" id="yourBox" onmousedown="this.form.yourText.disabled=this.checked"/> </form>

A better solution could be:更好的解决方案可能是:

 var checkbox = document.querySelector("#yourBox"); var input = document.querySelector("#yourText"); var toogleInput = function(e){ input.disabled = !e.target.checked; }; toogleInput({target: checkbox}); checkbox.addEventListener("change", toogleInput);
 <input type="checkbox" id="yourBox"> <input type="text" id="yourText">

 function createInput( chck ) { if( jQuery(chck).is(':checked') ) { jQuery('<input>', { type:"text", "name":"meta_enter[]", "class":"meta_enter" }).appendTo('p.checkable_options'); } else { jQuery("input.meta_enter").attr('disabled','disabled'); } } createInput( chck );
 <input type="radio" name="checkable" class="checkable" value="3" /> <input type="radio" name="checkable" class="checkable" value="4" onclick="createInput(this)" />

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

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