0

I have research that in html you can add a custom attribute by simply adding data-* attribute inside html tag. I populate my select > option tag from my database:

<td>
  <select onchange='setattr(this)' id='pitemnamerow"+ cnt +"' class='pitemname select2bs4 tselect'>
    <option selected='selected'></option>
  </select>
</td>

My Jquery and already set my custom tag

for (i in data.branditms) {
      $('#pitemname'+brndid.id).append($('<option>', {
      value: data.branditms[i]['item_id'],
      text: data.branditms[i]['item_name'],
      data-um: data.branditms[i]['um'], //custom-tag
}));

DOM result:

<select onchange="setattr(this)" id="pitemnamerow1" class="select2bs4 pitemname tselect select2-hidden-accessible" data-select2-id="pitemnamerow1" tabindex="-1" aria-hidden="true">    
   <option selected="selected" data-select2-id="81"></option>
   <option value="0-RKM51" data-um="PC/s" data-select2-id="84">0-RING 2"DIAMETER</option>
   <option value="UYD983" data-um="M" data-select2-id="84">Parts Wheel</option>
</select>

now when i try to access the custom attribute value it says undefine:

function setattr(brnditem){
    var test = $(this).find('.pitemname').data('um');
    console.log(test);  
}

PS: My table row and select > options are also dynamic.

Any idea?

5
  • You don't have any attribute with the name data. what's the value you expect to get? Commented Nov 25, 2020 at 5:54
  • i added it dynamically in my jquery. Commented Nov 25, 2020 at 5:56
  • can you take screenshot of your html tags in inspect mode and attach it to the question because I don't see attribute added name data Commented Nov 25, 2020 at 6:00
  • I have update my question. Commented Nov 25, 2020 at 6:05
  • I posted an answer @jzoler check it out Commented Nov 25, 2020 at 6:10

2 Answers 2

1

Try checking this:

      var test = $(brnditem).find('option:selected').data('um');

also make sure the function was defined right before calling it on the 'select' tag

Sign up to request clarification or add additional context in comments.

1 Comment

still undefined :(
0

You should call data() instead attr(), rewrite you code like this :

function setattr(brnditem)
{
  var test = $(brnditem).find("option:selected").data('um');
  console.log(test);  
}

11 Comments

i think there's something wrong with my code. I tried your code but still undefined. please see updated question.
I think you shoudl use brnditem in setattr() instead of this
$(brnditem).find('.pitemname').data('um'); still undefined.
how do you call setattr() and what do you pass as a parameter?
onchange='setattr(this)' i have included this in my question.
|

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.