javascript tutorial - [Solved-5 Solutions] Disable/enable an input with jQuery? - javascript - java script - javascript array



Problem:

	$input.disabled = true;
or
$input.disabled = "disabled";
click below button to copy the code. By JavaScript tutorial team

Which is the standard way? And, conversely, how do we enable a disabled input?

Solution 1:

Just for the sake of new conventions && making it adaptable going forward (unless things change drastically with ECMA6(????):

$(document).on('event_name', '#your_id', function() {
    $(this).removeAttr('disabled');
});
click below button to copy the code. By JavaScript tutorial team

and

$(document).off('event_name', '#your_id', function() {
    $(this).attr('disabled','disabled');   
});
click below button to copy the code. By JavaScript tutorial team

Solution 2:

// Disable #x
    $( "#x" ).prop( "disabled", true );
    // Enable #x
    $( "#x" ).prop( "disabled", false );
click below button to copy the code. By JavaScript tutorial team

Sometimes we need to disable/enable the form element like input or textarea. Jquery helps we to easily make this with setting disabled attribute to "disabled". For e.g.:

  //To disable 
  $('.someElement').attr('disabled', 'disabled');
click below button to copy the code. By JavaScript tutorial team

To enable disabled element we need to remove "disabled" attribute from this element or empty it's string. For e.g:

//To enable 
$('.someElement').removeAttr('disabled');

// OR we can set attr to "" 
$('.someElement').attr('disabled', '');
click below button to copy the code. By JavaScript tutorial team

Solution 3:

$("input")[0].disabled = true;
or
$("input")[0].disabled = false;
click below button to copy the code. By JavaScript tutorial team

Solution 4:

We can put this somewhere global in our code:

$.prototype.enable = function () {
    $.each(this, function (index, el) {
        $(el).removeAttr('disabled');
    });
}

$.prototype.disable = function () {
    $.each(this, function (index, el) {
        $(el).attr('disabled', 'disabled');
    });
}
click below button to copy the code. By JavaScript tutorial team

And then we can write stuff like:

$(".myInputs").enable();
$("#otherInput").disable();
click below button to copy the code. By JavaScript tutorial team

Solution 5:

If we just want to invert the current state (like a toggle button behaviour):

$("input").prop('disabled', ! $("input").prop('disabled') );
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Disable/enable an input with jQuery?