0

I'm fetching some data using JSON. According to data the HTML table is created. Each item has button. When I click on specific button I want to show alert window with button ID.

This is how I'm fetching data and populating HTML table:

function updateStations(){
    $.ajax({
        url: "scanstations.php",
        type: 'POST',
        cache: false,
        success: function (data){
            var jsonData = JSON.parse(data); 
            var tabledata;
            for (var i = 0; i < jsonData.stations.length; i++){
                tabledata += '<tr styls="padding-top:4px"><td>' + jsonData.stations[i].ID + '</td><td>' + jsonData.stations[i].IP + '</td><td><button class="btn btn-primary margin-top-5px" ';
                tabledata += ' id="' + jsonData.stations[i].IP + '"> <span >ButtonTitle</span></button></td></tr>';
            }
            console.log(jsonData);
            $('#listOfStations').html(tabledata);
        }
    })
}

How to create event for buttons?

I had tried on this way:

 $(document).ready(function () {

    $('.btn-primary').on('click', () =>{
        alert($(this).attr("id"));
    }); });

But doesn't work.

Josef
  • 2,430
  • 5
  • 29
  • 56
  • 1
    You are binding a click event to an element that is already in the DOM. But it cannot find it as it doesn't exist yet, so it will not work. As such, you need to bind to the document that does exist, and then test look for element. `$( document ).on( 'click', '.btn-primary', () => {});` – CHEWX May 13 '19 at 07:22
  • This works but why i get for alert($(this).attr("id")); as result: undefined? The id is assigned to each button. – Josef May 13 '19 at 07:49
  • 1
    Because you are using ES6. `this` is scoped differently. To fix this, change `() => {}` to `function() {}` and then `$(this)` will work as expected. – CHEWX May 13 '19 at 15:54

0 Answers0