Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

281
Views
How to get the value of an data-* attribute from a dynamically created select in a table when I change an option

I want to get the value of an data-* attribute from a dynamically created select in a table when I change an option. I am getting an "Uncaught ReferenceError: index is not defined".

The creating HTML is:

html += "<td style='width : 1%; white-space: nowrap;'><select name='parRating'>"
for (let i = 0; i <= paraArray; i++) {
    html += "<option name='parRatingOption' data-index='" + i + "' value='" + parIdArray[i] + "'>" + parRatingArray[i] + "</option>"
};
html += "</select></td>";

The option change catch is:

$('#showPatientPARForm').on( 'change', 'select[name="parRating"]', function (e) {
    e.preventDefault();
    alert("this.value: " + this.value);//works
    alert("this.data-index: " + this.data-index);//Uncaught ReferenceError: index is not defined
});

I have also tried:

alert("this.attr('data-index'): " + $(this).attr("data-index")); //undefined

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to make sure to target the data-attribute correctly, the value of the option gets returned from the parent selector (select), but the option itself needs to be accessed differently. Use dataset to target data attributes.

let paraArray = ['one','two','three'];
let parIdArray = ['idOne','idTwo','idThree'];
let parRatingArray = [1,2,3];

let html = '';
html += "<td><select name='parRating'>";
for (let i = 0; i < paraArray.length; i++) {
    html += "<option name='parRatingOption' data-index='" + i + "' value='" + parIdArray[i] + "'>" + parRatingArray[i] + "</option>";
}

html += "</select></td>";

$('#showPatientPARForm table').append(html);

$('#showPatientPARForm').on( 'change', 'select[name="parRating"]', function (e) {
    e.preventDefault();
   
    alert("this.value: " + this.value);//works
    
    // select the data attribute correctly:
    //alert(this.options[this.options.selectedIndex].dataset.index);
    alert(this.options.selectedIndex)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showPatientPARForm">
  <table></table>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!