9

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

1
  • @VisioN See my update. I needed to change the DOM element and to my knowledge, I can't use data to do that (hence the use of attr). Commented Jan 23, 2013 at 15:08

3 Answers 3

8
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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Not really sure what the problem is, but since you are using .data() you might as well keep using it in your if/else. Doing .attr('data-state') saves it on the DOM element itself (visible when you inspect the element), while with .data('state') it is invisible, and also faster.

Also if you use the ternary operator you can make it into 1 small line:

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

1 Comment

I needed to change the DOM element and to my knowledge, I can't use data to do that (hence the use of attr).
3
site.data('state', (site.data('state') == 'enabled' ? 'disabled' : 'enabled'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.