2

Im having a problem setting options to an array value in a jQuery plugin using data attributes.

If I reference the data attribute using a class selector

  $('.tm-input').tagsManager(
    {
    prefilled: $('.tm-input').data('load')
    })

It works but all the elements get the same values. If I reference using "this" it sets the correct values but it comes across as a string not an array.

  $('.tm-input').tagsManager(
    {
    prefilled: $(this).data('load')
    })

I've tried using JSON.parse() but I get an error about an unexpected character. Any help would be appreciated!

2
  • 1
    Show the strings that appear in the data-attributes. The problem is most likely because there is an illegal character somewhere in your data causing the JSON to be invalid. Commented Jun 26, 2014 at 1:51
  • post the html code also Commented Jun 26, 2014 at 1:52

1 Answer 1

5

Have you tried each

$('.tm-input').each (function () {
    $(this).tagsManager( { prefilled: $(this).data('load') });
});

Explanation:

When a selector has more than 1 element, applying a method to it will typically affect all of the elements, but retrieving a property will typically only return that property from the 1st element.

So when you use .tagsManager on your $('.tm-input') selector, you are applying .tagsManger to all of the elements. But when you set prefilled:$('.tm-input').data('load'), the data method is only grabbing the data from the first element in the list, every single time.

When you use each, it applies the logic inside of the each block to each element individually, rather than all of them at once, so when you use $(this).data('load'), it grabs the load attribute from each individual element as well.

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

3 Comments

BINGO! I would love to understand why that works, but I will not argue with success! Thanks chiliNUT!
@SteveO7 I've added an explanation to the answer.
So when adding methods that require element specific options like this, looping through with each is more precise. That makes sense.

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.