1

Below is the code.

<body>
<div class="test" >Test</div>

<script>
var count =1;
$('body').on('click', '.test', function () {

    $('.test').attr('data-count',count);
    count ++;
})

I want to add multiple values to data-count like this, data-count="1,2,3,4". How can i do that ?

3
  • 1
    If you comma-separate the values in the data attribute, how are you planning on reading them back in — have you thought about that? Commented Aug 25, 2014 at 19:02
  • basically i am planning to use shuffle.js and for that i need to set multiple values to data attribute. Based on my code above, everytime i click, i need to add this value dynamically to data-count, would appreciate if you can correct my code. Commented Aug 25, 2014 at 19:05
  • @user3751873 - You may accept the answer that you found most helpful by clicking the tick mark on the left of the answers posted. Commented Aug 26, 2014 at 7:11

3 Answers 3

1

A solution without global variables:

$('body').on('click', '.test', function () {

    var $this = $(this),
        count = $this.data('i') || 1,
        $test = $('.test');

    count++;
    $this.data('i', count);

    var result = [];

    for(var i = 1; i < count; i++){
        result.push(i);
    }

    $test.attr('data-count', result.toString());
});

http://jsfiddle.net/r7ny77s9/

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

1 Comment

or $test.data('count', result); and $test.data('count') to get the array back. I know the answer is old, that's why posted this comment so you can update your answer if you wish.
0

Similar to Alok Swain's Answer, saving data-* count as an array at the element

var count = 1;
var arr = [];
$(".test").data("count", arr);
$('body').on('click', '.test', function () {
    $('.test').data("count", arr.push(count));
    count++;
});

Comments

0
var count = 1;
var countArr = [];
$('body').on('click', '.test', function () {
    countArr.push(count);
    $('.test').attr('data-count', countArr.join(","));
    count ++;
});

Edit: without using the second variable

var count = 1;

$('body').on('click', '.test', function () {    
  var testVal = $('.test').attr('data-count') === undefined ? count : $('.test').attr('data-count') + "," + count;
  $('.test').attr('data-count', testVal);
    count ++;
});

1 Comment

Thanks alot Alok it worked, i didnt see any example on jquery website, why is this so ?

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.