Reputation: 8050
First, the fiddle.
$('#enableButtonB').click(function (e) {
if($(e.target).is(':checked'))
{
$('#myButtonB').removeProp('disabled');
alert('Enable Button B');
}
else
{
$('#myButtonB').prop('disabled', true);
alert('Disable Button B');
}
});
I'm trying to use jQuery's .prop()
and removeProp()
methods to enable and disable a button based on some criteria. It seems to work fine until removeProp()
is called on the element. After that any subsequent calls to prop()
fail to disable to button.
What's the proper way to enable and disable an element repeatedly?
Upvotes: 22
Views: 22731
Reputation: 339
This line will act as toggle disabled function:
$('#myButtonB').prop('disabled', !$('#myButtonB').prop('disabled'));
If you use it inside a jquery function you can use it like:
$('#enableButtonB').on('click', function() {
$('#myButtonB').prop('disabled', !$('#myButtonB').prop('disabled'));
});
Upvotes: 2
Reputation: 22241
First, http://jsfiddle.net/iambriansreed/KxGVa/
The jQuery docs are great. removeProp
says:
Note: 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 tofalse
instead.
Change:
.removeProp('disabled')
...to...
.prop('disabled', false)
...and...
.prop('disabled', 'disabled')
...to...
.prop('disabled', true)
Upvotes: 17
Reputation: 93
Try if this short function solves your needs:
$("#enableButtonB").click(function(){
$("#myButtonB").prop('disabled', function (_, val) { return ! val; });
});
Creds to user Explosion Pills for that sweet function :)
Upvotes: 6
Reputation: 92893
Instead of
.removeProp('disabled')
use
.prop('disabled',false)
Fiddle: http://jsfiddle.net/kqnZz/6/
Upvotes: 26