Avatar of impressionexpress
 asked on

trying to add option with data attribute using jquery

This is what I have so far but the data attributes are not added. what am I doing wrong
  .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


Avatar of undefined
Last Comment
Chris Stanyon

8/22/2022 - Mon
Chris Stanyon

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,

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 ?
Chris Stanyon

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
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy

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

Chris Stanyon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question