user13927150
user13927150

Reputation: 55

how to get record of a row in table whose corresponding button is clicked in jQuery

I am working on Laravel project, I have some country information stored in database, using AJAX request I am retrieving record from database, and appending it in my HTML table, the rows(cells) of table are editable so, my main goal is to edit them and update them in database, issue I am facing is that, I have added onClick event on update button, but it is automatically called when loop is in progress, but when I click button manually it doesn't work, I want that relevant row record whose button is clicked so I can update it.

demo screenshot enter image description here HTML code

<table class="table table-bordered table-responsive-md table-striped text-center" id="tblData">
        <thead>
            <tr>
                <th class="text-center">ID</th>
                <th class="text-center">Country Name</th>
                <th class="text-center">Region</th>
                <th class="text-center">Pressing Social Challenge</th>
                <th class="text-center">Ethnic Conflict</th>
                <th class="text-center">Civil Strife</th>
                <th class="text-center">Social Upheaval</th>
                <th class="text-center">Health Risk</th>
                <th class="text-center">SI SCORE</th>
                <th class="text-center">Update</th>
            </tr>
        </thead>
        <tbody id="mapDataRecord">

        </tbody>
    </table>

JS code

$(document).ready(function() {
    load_data();

});


function load_data()
{
    getRecords='getRecords';
    $.ajaxSetup({
        headers: 
        {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        }
    });
    $.ajax({
        url:"getMapData",
        method:"POST",
        data:'getRecords='+getRecords,
        success:function(data)
        {
            // $('#mapDataRecord').html(data);
            var jsonData = JSON.parse(data);
            var dataAppend='';
            for (let index = 0; index < jsonData.length; index++) 
            {
                dataAppend+="<tr><td class='text-center font-weight-bold ids'>"+
                jsonData[index]['id']+"</td><td class='text-center font-weight-bold tester'>"+
                jsonData[index]['countryName']+"</td><td class='text-center font-weight-bold'>"+
                jsonData[index]['region']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['pressing_social_challenge']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['ethnic_conflict']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['civil_strife']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['social_upheaval']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['health_risk']+"</td><td class='text-center font-weight-bold'>"+
                getSiScore(jsonData[index])+"</td><td class='text-center'><button class='btn btn-primary' id='updateData' onclick='"+
                updateRecord(jsonData[index])+"'>Update</button></td></tr>";
            }
            $('#mapDataRecord').html(dataAppend);
            // console.log(jsonData[0]);
        }
    });
}

function getSiScore(array)
{
    var value = (array['pressing_social_challenge']*(10/100))+(array['ethnic_conflict']*(30/100))+(array['civil_strife']*(20/100))+(array['social_upheaval']*(20/100))+(array['health_risk']*(20/100));
    // return value;
    if(value>5)
    {
        return 5;
    }
    else
    {
        return value.toFixed(1);
    }
}

function updateRecord(data){
    console.log(data);
}

Upvotes: 1

Views: 258

Answers (3)

LilFlower
LilFlower

Reputation: 61

I'm trying to sort out the issue by doing few changes on the code:

    $(document).ready(function() {
    load_data();

});

var jsonData = {};

function load_data()
{
    getRecords='getRecords';
    $.ajaxSetup({
        headers: 
        {
            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        }
    });
    $.ajax({
        url:"getMapData",
        method:"POST",
        data:'getRecords='+getRecords,
        success:function(data)
        {
            // $('#mapDataRecord').html(data);
            jsonData = JSON.parse(data);
            var dataAppend='';
            for (let index = 0; index < jsonData.length; index++) 
            {
                dataAppend+="<tr><td class='text-center font-weight-bold ids'>"+
                jsonData[index]['id']+"</td><td class='text-center font-weight-bold tester'>"+
                jsonData[index]['countryName']+"</td><td class='text-center font-weight-bold'>"+
                jsonData[index]['region']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['pressing_social_challenge']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['ethnic_conflict']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['civil_strife']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['social_upheaval']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['health_risk']+"</td><td class='text-center font-weight-bold'>"+
                getSiScore(jsonData[index])+"</td><td class='text-center'><button class='btn btn-primary' id='updateData' data-index='"+ index + "'>Update</button></td></tr>";
            }
            $('#mapDataRecord').append($(dataAppend));
            // console.log(jsonData[0]);
        }
    });
}

function getSiScore(array)
{
    var value = (array['pressing_social_challenge']*(10/100))+(array['ethnic_conflict']*(30/100))+(array['civil_strife']*(20/100))+(array['social_upheaval']*(20/100))+(array['health_risk']*(20/100));
    // return value;
    if(value>5)
    {
        return 5;
    }
    else
    {
        return value.toFixed(1);
    }
}

function updateRecord(index){
    console.log(jsonData[Number(index)]);
}

$(document).on('click', "#updateData", function () {
    console.log(jsonData(Number($(this).attr("data-index"))));
});
  1. Assigned jsonData variable outside if the function.
  2. Replaced $('#mapDataRecord').html(dataAppend); with $('#mapDataRecord').append($(dataAppend));
  3. changed updateRecord function.

EDIT: Removed the click event from inside the for loop and added a common click event. You can apply same logic on your originally posted code.

Upvotes: 1

badateverything
badateverything

Reputation: 1

updateRecord function automatically runs because you are actually caling the function with this line "updateRecord(jsonData[index])". To solve the issue you can add "index" as a data attribute to the button

"<button data-index=" + index + ">Edit</button>"

then attach a listener to body element after the for loop and check the element is button and has a attribute called index. If it is then you can call the update function.

document.body.onclick = function(event) {
   var index = event.target.getAttribute("index");
   if (index){
     updateRecord(jsonData[index]);
   }

Upvotes: 0

Xiko
Xiko

Reputation: 44

You should try to put an alert to see if the data are ok.

you button id is always 'updateData' maybe there is a probleme with it, like you click on it and then javascript try to find the object with this id but as they are many it could just answer 'undefined'.

EDIT: you are calling updateRecord in your 'for' instead of putting the fonction inside the onClick , just take care of the quote and it should be OK

 for (let index = 0; index < jsonData.length; index++) 
            {
                dataAppend+="<tr><td class='text-center font-weight-bold ids'>"+
                jsonData[index]['id']+"</td><td class='text-center font-weight-bold tester'>"+
                jsonData[index]['countryName']+"</td><td class='text-center font-weight-bold'>"+
                jsonData[index]['region']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['pressing_social_challenge']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['ethnic_conflict']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['civil_strife']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['social_upheaval']+"</td><td class='text-center' contenteditable>"+
                jsonData[index]['health_risk']+"</td><td class='text-center font-weight-bold'>"+
                getSiScore(jsonData[index])+"</td><td class='text-center'><button class='btn btn-primary' id='updateData' onclick='updateRecord("+jsonData[index])+"'>Update</button></td></tr>";
            }


Should work

Upvotes: 1

Related Questions