Glyn
Glyn

Reputation: 1995

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

Upvotes: 0

Views: 602

Answers (1)

prettyInPink
prettyInPink

Reputation: 3444

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>

Upvotes: 1

Related Questions