Skip to content

Instantly share code, notes, and snippets.

@jbottigliero
Created April 30, 2012 19:58
Show Gist options
  • Save jbottigliero/2562233 to your computer and use it in GitHub Desktop.
Save jbottigliero/2562233 to your computer and use it in GitHub Desktop.
jQuery Toggle Disabled
<input id="test_input" type="text" value=""/>
<button id="disabler">Disable Input</button>
<script>
$('#disabler').on('click', function(){
// No callback
// $('#test_input').toggleDisabled();
// With callback
$('#test_input').toggleDisabled(function(el, disabled){
if(disabled){
el.value = 'DISABLED, YO!';
} else {
el.value = '';
}
});
});
</script>
(function($){
$.fn.toggleDisabled = function(callback){
return this.each(function(){
var disabled, $this = $(this);
if($this.attr('disabled')){
$this.removeAttr('disabled');
disabled = false;
} else {
$this.attr('disabled', 'disabled');
disabled = true;
}
if(callback && typeof callback === 'function'){
callback(this, disabled);
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment