Search code examples
javascriptjqueryfindclickable

jquery clickable row: how to find the value i need in ${this}


i'm stuck with a table, in which i would like every row to be clickable. Clicking on a row will start a function, using the value of the first cell of the row (i put it in a <p>) as a parameter, here is the table below.

 for (var i=0;i<changeList.length;i++){
$('#tableOfChanges').append('<tr class="changeRow"><td  style="width:10%"><p id="changeId" value="'+changeList[i][0]+'">'+changeList[i][0]+'</p></td>'+
                                 '<td style="width:10%">'+changeList[i][1]+'</td>'+
                                 '<td style="width:20%">'+changeList[i][2]+'</td>'+
                                 '<td style="width:10%">'+changeList[i][3]+'</td>'+
                                 '<td style="width:5%">'+changeList[i][4]+'</td>'+
                                 '<td style="width:10%">'+changeList[i][5]+'</td>'+
                                 '<td style="width:10%">'+changeList[i][6]+'</td>'+
                                 '<td style="width:10%">'+changeList[i][7]+'</td></tr>');
}
}

And here is the function to make the row clickable, and use the first cell of the row as a parameter of a function. (for the exemple I only use "alert()" function)

$(document).on('click','.changeRow',function(){

var changeNumber=$(this).find('#changeId').val();

alert(changeNumber);
})

My problem is with this code, the alert function only returns an empty value. I tried many options but the alert either displays nothing, or "[object Object]"

Would someone have experienced a similar situation? Many thanks in advance for your help


Solution

  • <p> elements don't have a value, use a data-* attribute to hold user-defined data, and access it with .data(). You can't repeat IDs, so you should use a class.

    var changeList = [
      [1, 2, 3, 4, 5, 6, 7, 8],
      [10, 11, 12, 13, 14, 15, 16, 17],
      [19, 20, 21, 22, 23, 24, 25, 26]
    ];
    
    for (var i = 0; i < changeList.length; i++) {
      $('#tableOfChanges').append('<tr class="changeRow"><td  style="width:10%"><p class="changeId" data-value="' + changeList[i][0] + '">' + changeList[i][0] + '</p></td>' +
        '<td style="width:10%">' + changeList[i][1] + '</td>' +
        '<td style="width:20%">' + changeList[i][2] + '</td>' +
        '<td style="width:10%">' + changeList[i][3] + '</td>' +
        '<td style="width:5%">' + changeList[i][4] + '</td>' +
        '<td style="width:10%">' + changeList[i][5] + '</td>' +
        '<td style="width:10%">' + changeList[i][6] + '</td>' +
        '<td style="width:10%">' + changeList[i][7] + '</td></tr>');
    }
    
    $(document).on('click', '.changeRow', function() {
      var changeNumber = $(this).find('.changeId').data("value");
      alert(changeNumber);
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table id="tableOfChanges">
    </table>