Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle data attribute with jQuery?

I need to toggle between two possible values for a data attribute.

If data-state is equal to enabled then I want to change it to disabled and vice versa.

$('.sites .state').on('ajax:success', function(data, status, xhr) {
   var site = $(this).parents('article').first();

   if (site.data('state') == 'enabled') {
     site.attr('data-state', 'disabled');
   } else {
     site.attr('data-state', 'enabled');
   }
});

NOTE: I needed to change the DOM element and to my knowledge, I can't use data to do that (hence the use of attr).

like image 462
Shpigford Avatar asked Jan 23 '13 14:01

Shpigford


2 Answers

site.data('state', (site.data('state') == 'enabled' ? 'disabled' : 'enabled'))
like image 145
Robin Maben Avatar answered Oct 22 '22 15:10

Robin Maben


site.attr('data-state', 'disabled');

Should be

site.data('state', 'disabled');

When an element is created the data-<value> attribute can be used in initialize the data property, but after that you have to use the jQuery.data() method to fetch or modify the data.

While $(el).data('<data-name>') returns the value, $(el).data('<data-name>', value) set the data value.

Updated: Based on the updated requirement

$('div').attr('data-state', $('div').attr('data-state') == 'enabled' ? 'disabled' : 'enabled')

Fiddle

like image 28
Arun P Johny Avatar answered Oct 22 '22 14:10

Arun P Johny