We help IT Professionals succeed at work.

trying to add option with data attribute using jquery

impressionexpress
impressionexpress asked
on
This is what I have so far but the data attributes are not added. what am I doing wrong
$('select[name="slc_pc"]')
  .append($('<option />')  // Create new <option> element
    .val('Hello')            // Set value as "Hello"
    .text('Hello')           // Set textContent as "Hello"
    .prop('selected', true)  // Mark it selected
    .data({                  // Set multiple data-* attributes
      token: 'abc'
    })
  );

Open in new window

Comment
Watch Question

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Hey there,

Are you sure they're not being added. They won't show up in your inspector or the console, so you won't be able to 'see' if they've been added. You'll need to examing the data property in code to check them. Quick way is to select the <option> in your Inspector and then type $($0).data() into the inspectors command line - that will output the data attributes on your element,

Author

Commented:
I do see it showing up when inspecting element, but the data attribute is not there. also when I get the value of the data-token its coming back undefined ?
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
I doubt you see it showing up when you inspect - that's just not how dynamic data elements work.

You say it's coming back as undefined - how exactly are you trying to retrieve the value?

You can see a working demo here: https://jsfiddle.net/ChrisStanyon/v0dfzqL7/Just click the button and you'll see the data

Author

Commented:
I see the new option that was added but without the data-token. I can also check if undefined on line 6, but im more curious as to why its return undefined
		var report_id = $("#report_list").find(":selected").val();
		var token = $("#report_list").find(':selected').attr('data-token');
		
		var fetch_str = '?token=' + token;
		
		if(token == ''){
			fetch_str = '?id=' + report_id;
		}

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
OK. Like I said - you won't be able to 'see' the data attributes - when you add them dynamically like that, they're added internally, so they won't show up in the Inspector.

When you add dynamic data attributes like this, you need to use the data() method to retrieve them and not the attr() method:

var token = $(':selected', '#report_list').data('token');

Open in new window

I've updated the fiddle to show this working