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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15140237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:39:30  来源:igfitidea点击:

enabled and disabled text input on checkbox checked and unchecked

javascript

提问by Reham Fahmy

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

任何帮助〜谢谢

回答by Minko Gechev

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" />

回答by Rayfloyd

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 的答案相同,但我觉得它更优雅。

回答by B. Branchard

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">

回答by Yevgen Kharchenko

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>

回答by Walid Rezk Dev

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)" />