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).
site.data('state', (site.data('state') == 'enabled' ? 'disabled' : 'enabled'))
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With