سؤال

I'm trying to prevent text from being entered in a textbox unless a checkbox that corresponds with the textbox is checked.

// Validate "Other" textbox
var isOther = document.getElementById("isOther");
isOther.addEventListener("input", function (evt) {
     // Checkbox must be checked before data can be entered into textbox
     if (isOther.checked) {
          document.getElementById("other").disabled = false;
     } else {
          document.getElementById("other").disabled = true;
     }
});
هل كانت مفيدة؟

المحلول

Do not use disabled. Instead use readonly. During document load, uncheck and disable the inputs:

<input type="checkbox" id="isOther" />
<input type="text" id="other" readonly />

And use this script.

// Validate "Other" textbox
var isOther = document.getElementById("isOther");
var other = document.getElementById("other");
isOther.addEventListener("click", function () {
    other.readOnly = !isOther.checked;
});
other.addEventListener("focus", function (evt) {
     // Checkbox must be checked before data can be entered into textbox
    other.readOnly = !isOther.checked;
});

Longer version.

// Validate "Other" textbox
var isOther = document.getElementById("isOther");
var other = document.getElementById("other");
isOther.addEventListener("click", function () {
     if (isOther.checked) {
          other.readOnly = false;
     } else {
          other.readOnly = true;
     }
});
other.addEventListener("focus", function (evt) {
     // Checkbox must be checked before data can be entered into textbox
     if (isOther.checked) {
          this.readOnly = false;
     } else {
          this.readOnly = true;
     }
});

Fiddle: http://jsfiddle.net/praveenscience/zQQZ9/1/

Fiddle: http://jsfiddle.net/praveenscience/zQQZ9/

نصائح أخرى

My solution uses jQuery library. Here's a fiddle: http://jsfiddle.net/8LZNa/

Basically I'm disabling the input on page load:

<input name="isOther" type="checkbox" id="isOther" /><br />
<input type="text" id="other" disabled/>

... and when isOther changes it will make sure it is checked, and change the state to enabled. Or change back to disabled.

$('input[name=isOther]').change(function(){
    if($(this).is(':checked')) {
        $("#other").removeAttr('disabled');
    }
    else{
       $("#other").attr('disabled','disabled');
    }    
});

You can do this:

document.getElementById( 'isOther' ).onChange = function(){
    document.getElementById("other").disabled = !this.checked;
};

Without the use of jQuery or disabled property:

HTML

<input type="checkbox" id="x" value="Enable textbox" onclick="test(this);" />
<input type="text" id="y" readonly />

JAVASCRIPT

function test(checkbox) {
    if(checkbox.checked) {
        document.getElementById('y').readOnly = false;
    }
    else {
        document.getElementById('y').readOnly = true;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top