How to switch data attribute using jQuery?

I need to switch between two possible data attribute values.

If data-stateequal enabled, then I want to change it to disabledand 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 not use datafor this (therefore, use attr).

+5
source share
3 answers
site.attr('data-state', 'disabled');

Must be

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

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

$(el).data('<data-name>') , $(el).data('<data-name>', value) .

:

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

Fiddle

+3

, , .data(), if/else. .attr('data-state') DOM ( ), .data('state') , .

, , 1 :

site.attr('data-state', site.data('state') === 'enabled' 
    ? 'disabled' 
    : 'enabled');
+3
site.data('state', (site.data('state') == 'enabled' ? 'disabled' : 'enabled'))
+1
source

All Articles