Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle disabled property using jQuery's prop() doesn't work

Tags:

jquery

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?

like image 298
Jason Towne Avatar asked Jun 06 '12 18:06

Jason Towne


People also ask

How to disable toggle button in jQuery?

How to turn off toggle in jquery? find(“:input[type='text']”) // Find text elements in that row. . attr('disabled',false). toggleClass('disabled') // Enable them. .

How check textbox is enabled or disabled in jquery?

You can use $(":disabled") to select all disabled items in the current context. To determine whether a single item is disabled you can use $("#textbox1").is(":disabled") . Save this answer.

How to use prop in jQuery?

The prop() method sets or returns properties and values of the selected elements. When this method is used to return the property value, it returns the value of the FIRST matched element. When this method is used to set property values, it sets one or more property/value pairs for the set of matched elements.

How to get property of element in jQuery?

prop() method provides a way to explicitly retrieve property values, while . attr() retrieves attributes. For example, selectedIndex , tagName , nodeName , nodeType , ownerDocument , defaultChecked , and defaultSelected should be retrieved and set with the . prop() method.


3 Answers

Instead of

.removeProp('disabled')

use

.prop('disabled',false)

Fiddle: http://jsfiddle.net/kqnZz/6/

like image 149
Blazemonger Avatar answered Oct 14 '22 15:10

Blazemonger


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 to false instead.

Change:

.removeProp('disabled')

...to...

.prop('disabled', false)

...and...

.prop('disabled', 'disabled')

...to...

.prop('disabled', true)
like image 17
iambriansreed Avatar answered Oct 14 '22 15:10

iambriansreed


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 :)

like image 6
Unibyte Avatar answered Oct 14 '22 15:10

Unibyte