• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

164
Vistas
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

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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>

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda