Thursday, 22 June 2017

Disable or enable input field using jQuery and JavaScript ~ GNIITHELP

JavaScript :
We can disable or enable an input box by setting property true or false respectively by using below code.
Code of input box
Name: <input type="text" id="myName">

To Disable input box.
document.getElementById("myName").disabled = true;

To Enable input box.
document.getElementById("myName").disabled = false;

jQuery :
If you are using jQuery 1.6+ then you should use the .prop() function to disable or enable input field.
$("input").prop('disabled', true);
$("input").prop('disabled', false);

Above code will disable all the input fields, if you want to disable or enable particular field, then you should use class or id of that particular input field.
Name: <input type="text" id="myName" class="myName"> 
$("#myName").prop('disabled', true);  // using id of input box
$(".myName").prop('disabled', false); // using class of input box

If you are using jQuery 1.5 or below then you should use the .attr() function.
To disable input field:
$("input").attr('disabled', 'disabled');

To enable input field: 
$("input").removeAttr('disabled');

There is also .removeProp like .removeAttr in jQuery 1.6 but we should not use it because once you use removeProp you can not again disable it.

No comments:

Post a Comment