Disable or enable an input field with jQuery
For jQuery 1.6 or above there is prop() function and lower jQuery versions have attr() function which can be used to disable or enable an input field. Further more DOM object’s disabled property also works with any version of jQuery to disable or enable an input field.
Single Input
If you are dealing with just an element then relying on the actual DOM object is bit faster than other methods which I will mention below.
// assuming an event handler thus 'this'
this.disabled = true;
// assuming an event handler thus 'this'
this.disabled = true;
jQuery 1.6+ using prop()
$('#your_id').on('event_name', function() {
$("input").prop('disabled', true); //Disable input
$("input").prop('disabled', false); //Enable input
})
$('#your_id').on('event_name', function() {
$("input").prop('disabled', true); //Disable input
$("input").prop('disabled', false); //Enable input
})
jQuery 1.5 and below using attr()
$('#your_id').on('event_name', function() {
$("input").attr('disabled','disabled'); //Disable input
$("input").removeAttr('disabled'); //Enable input
})
$('#your_id').on('event_name', function() {
$("input").attr('disabled','disabled'); //Disable input
$("input").removeAttr('disabled'); //Enable input
})
Points worth mentioning
The advantage to using the prop() or attr() methods is that you can set the property for a bunch of selected items.
In 1.6 there is a removeProp() method that sounds like removeAttr() but never use it on native properties like ‘disabled‘ as per jQuery documentation says:
Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
If you want to let disable/enable work for elements inserted into the DOM at any point then you should replace
$('#your_id').on('event_name', function() {...})
with
$(document).on('event_name', '#your_id', function() {...})
because the former is only for those extant at that moment.
출처 : http://fellowtuts.com/jquery/disable-or-enable-an-input-field-with-jquery/
'Story > Jquery' 카테고리의 다른 글
jQuery Selectors (0) | 2016.01.19 |
---|---|
detect-mobile-devices 모바일 체크 (0) | 2015.09.21 |
jQuery Number Plugin (0) | 2015.03.16 |
javascript 줄바꿈 처리 nl2br (0) | 2015.03.16 |
jQuery Selectbox plugin (0) | 2015.03.10 |