0

I'm passing some values to a javascript function from an anchor tag as follows:

    <a href="http:///www.example.com" data-json='{ "next_id": 3, "prev_id":1}' id="2">Click here</a>

The js function looks a bit like this:

$(document).on( 'click', 'a', function( event ) {
    console.log($(this).data());
    var this_id = this.id;
    var next_id = $(this).data(next_id);
    var prev_id = $(this).data(prev_id);
}

The console shows the following for $(this).data()

Object {json: Object}
    json: Object
        next_id: 3
        prev_id: 1

But any attempt to read the values of next_id or prev_id fail:

var prev_id = $(this).data(prev_id);

just returns [object Object]

var prev_id = $(this).data("prev_id"); 

or

var prev_id = $(this).data('prev_id');

Returns Undefined

I think I'm missing something fairly obvious - really grateful for any pointers

1
  • 1
    try console.log($(this).data().json.next_id); it will give you the correct value. Commented May 26, 2016 at 11:32

1 Answer 1

4

You need to get the JSON using .data(key) where key is json, then you can get the next_id or prev_id property.

Use

 var next_id = $(this).data('json').next_id;
Sign up to request clarification or add additional context in comments.

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.