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

Answers:

Answer

You just need to add a ! in front of 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" />

Answer

A jQuery solution could be this one:

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

It is the same as Minko's answer but I find it more elegant.

Answer

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

Answer

Try it. If you use a label then add onmousedown to it

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

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.