5

I'm searching for this sometime. Found this old article and this. But not working for me.

My Problem is : I cannot set incremented data-id to HTML Element via jQuery. I'm able to alert the same, But I failed to set in HTML. There is no change in the element if I inspect.

jQuery

$(document).ready(function() {    
   $("#search").click(function(){      
   var num = $(this).data('id');    
    num++; 
    $("span").text(num);
    $(this).data('id', num);
   });    
 });

I tried this also

$(this).data('id') === num;

Here is a jsFiddle Demo

I'm using v1.9.1 and no error in console. Its great if anyone can find the issue.

Community
  • 1
  • 1
Surjith S M
  • 6,642
  • 2
  • 31
  • 50

5 Answers5

8

All other answers are correct - fixing 'val' to val - that of course solves the NaN issue.

The problem however is:

I cannot set incremented data-id to HTML Element via jQuery. I'm able to alert the same, But I failed to set in HTML. There is no change in the element if I inspect.

jQuery uses internal representation (1) for data. If you want to see data-id in inspector you need to use: $(this).attr('data-id', num);


(1) "Internal represenation":

All data is stored inside a property of the jQuery object named cache. Log the contents of $.cache in your console to see all data and events associated with any DOM element.

See: https://stackoverflow.com/a/4385015/775359

Community
  • 1
  • 1
Mars Robertson
  • 12,673
  • 11
  • 68
  • 89
2

The problem is in this line.

$(this).data('id', 'num');

num should be a variable, not a string.

Change it to this and it will work fine:

$(this).data('id', num);
James Hibbard
  • 16,490
  • 14
  • 62
  • 74
  • Sorry that was a Typo, Not Working with variable too – Surjith S M Jan 07 '14 at 13:04
  • Your fiddle works for me. When you click the div, the number is increased. What is it that you are expecting? – James Hibbard Jan 07 '14 at 13:15
  • I cannot set incremented data-id to HTML Element. See yourself by inspecting. – Surjith S M Jan 07 '14 at 13:16
  • 1
    But you evidently can, otherwise the number in the span would not increase. If you are expecting to see the data attribute updated on the element, see here for why that won't work: http://stackoverflow.com/questions/4384784/jquery-data-storage/4385015#4385015 – James Hibbard Jan 07 '14 at 13:18
2

Try this to get:

$(this).attr('data-id');

and this to set attribue:

$(this).attr('data-id', num);
Oleg
  • 22,300
  • 9
  • 68
  • 84
1

Standard Pure Javascript data-attr

try this

this.dataset['id']=num;

or

this.dataset.id=num;

http://jsfiddle.net/JU4H4/8/

EDIT based on the comments and also why i don't use jaquery

here is a partial function for data-attr taken from jquery's code.(i don't use jquery)

function dataAttr( elem, key, data ) {
        var name;

        // If nothing was found internally, try to fetch any
        // data from the HTML5 data-* attribute
        if ( data === undefined && elem.nodeType === 1 ) {
                name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
                data = elem.getAttribute( name );

                if ( typeof data === "string" ) {
                        try {
                                data = data === "true" ? true :
                                        data === "false" ? false :
                                        data === "null" ? null :
                                        // Only convert to a number if it doesn't change the string
                                        +data + "" === data ? +data :
                                        rbrace.test( data ) ? jQuery.parseJSON( data ) :
                                        data;
                        } catch( e ) {}

                        // Make sure we set the data so it isn't changed later
                        data_user.set( elem, key, data );
                } else {
                        data = undefined;
                }
        }
        return data;
}
cocco
  • 16,442
  • 7
  • 62
  • 77
  • There is no `dataset` property on jQuery collections? – Bergi Jan 07 '14 at 12:50
  • it's javascript. and it sets the data-attr – cocco Jan 07 '14 at 12:52
  • Of course jQuery is JavaScript, but there is no `dataset` in jQuery. Did you mean https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.dataset? – Bergi Jan 07 '14 at 12:56
  • yeah is that different? – cocco Jan 07 '14 at 12:57
  • yeah jquery does not point to the real this with $(this)... i didn't know that. you know .. i don't use jquery. – cocco Jan 07 '14 at 13:00
  • but it's the same. and as it's a standard... it's 100% better to use dataset vs data(bla,bla) – cocco Jan 07 '14 at 13:01
  • Actually jQuery's `data` method does not even set the data attributes (nor the `dataset` store), it only retrieves it. – Bergi Jan 07 '14 at 13:03
  • @cocco Your solution is working. But can I include `js` inside Jquery? – Surjith S M Jan 07 '14 at 13:04
  • jquery is a mix of js functions. so yes. you should first learn js then to make your scripts more compatible with ie6 use jquery – cocco Jan 07 '14 at 13:05
  • jquery is only here to make some scripts work with internet explorer 6, because almost all browsers and phones have standards now.so jquery is no needed anymore... but apparently ppl don't know that. – cocco Jan 07 '14 at 13:06
  • @cocco I wonder why jquery don't have this function :-( How about Zub's answer? – Surjith S M Jan 07 '14 at 13:10
  • this is a new standard in javascript 1.7. it works on all modern browsers.if you prefer Zub's jquery solution use that... – cocco Jan 07 '14 at 13:12
-1

Use the variable num, not the string 'num':

$(this).data('id', num);

Updated jsfiddle demo

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Sorry that was a Typo, Your fiddle is also not working. The data-id is not set to that element (Please see it by inspecting) – Surjith S M Jan 07 '14 at 13:06
  • @SurjithSM: Why would you need that? Of course you could simply use `this.dataset.id = num;` or `$(this).attr("data-id", num)` or `$(this).prop("dataset").id = num`, but why not use the internal datastore provided by jQuery that is working in all browsers? – Bergi Jan 07 '14 at 14:00
  • `.prop("dataset")` is also working.. But I will stick on to `attr` now – Surjith S M Jan 08 '14 at 04:57