big_smile
big_smile

Reputation: 1523

Change Assign ID Value of an element to the data attribute of another element

I have several HTML link elements, which all have a unique number ID.

These are all stored in a wrapper, which uses a data attribute called "data-color".

When the user clicks on the links, I want the data-color to take on the number ID of the link.

I thought I could use data(), but it doesn't seem to work.

Here is a JSFIDDLE.

Here is my HTML:

<div id="wrapper" data-color="01">

<span>Color Box</span>

<a class="ThumbnailBox" href="#" id="02">02</a>
<a class="ThumbnailBox" href="#" id="03">03</a>
<a class="ThumbnailBox" href="#" id="04">04</a>
<a class="ThumbnailBox" href="#" id="05">05</a>
<a class="ThumbnailBox" href="#" id="06">06</a>

</div>

Here is my Jquery:

(function ($) {
    $(document).ready(function () {

        $(".ThumbnailBox").click(function () {
            selectedcolor = $(this).attr('id');
            $('#wrapper').data('datacolor', selectedcolor);

        });
    });

})(jQuery);

Upvotes: 0

Views: 198

Answers (2)

rajesh kakawat
rajesh kakawat

Reputation: 10896

try something like this, you don't have to use data- to use it

$(".ThumbnailBox").click(function () {
    $('#wrapper').data('color', this.id);
});

to change the value in dom than use attr

$('#wrapper').attr('data-color', this.id);

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

Upvotes: 2

Sridhar R
Sridhar R

Reputation: 20418

you just try this code it working fine..

$(".ThumbnailBox").click(function () {
selectedcolor = $(this).attr('id');
    alert(selectedcolor)
$('#wrapper').attr('data-color', selectedcolor);
});

Here is updated fiddle http://jsfiddle.net/dLQHs/3/

Upvotes: 1

Related Questions