Craig Kuyper
Craig Kuyper

Reputation: 65

How can I pass the row id from a table with a button

I have a table I want to add a button to each row and edit the row in a form. I need to pass the LineNumber into my getjson request. how can I do that? Here is my table and my getjson. (edit)I just noticed I'm asking for LineNumber but what I really want is the id of the button pushed '+value.linenumber+'.

//table goes though a loop.
table_obj.append($('<tr><td>'+value.SLN+'</td><td  >'+value.Type+'</td><td     >
'+value.StopNumber+'</td><td>'+value.LoName+'</td><td >'+value.ReferenceNo+'</td>
<td class="hide" >'+value.TypeId+'</td><td class="hide" >'+value.LocationId+'</td>
<td class="hide" >'+value.lineNumber+'</td><td><button id='+value.lineNumber+'
onclick=edit()>Edit</button></td></tr>'));

//getjson
<script> function edit()
$.getJSON("editstops.php",{ LineNumber:$('#LineNumber').val() },stophandler)
var stophandler = function(data){
$("#SLNS").val(data[0].value.LoadNumber);
$("#Type").val(data[0].value.Type);
    $("#StopNumber").val(data[0].value.StopNumber);
$("#LoName").val(data[0].value.LoName);
$("#ReferenceNo").val(data[0].value.ReferenceNo);   
$("#TypeId").val(data[0].value.TypeId);
$("#LocationId").val(data[0].value.LocationId);
    $("#LineNumber").val(data[0].value.Linenumber);
};

</script>

Upvotes: 0

Views: 2903

Answers (1)

jszobody
jszobody

Reputation: 28911

In your button tag, you already have the line number specified as the ID attribute. You can just as easily pass it into the edit() function as an argument:

<button id='+value.lineNumber+' onclick="edit('+value.lineNumber+')">Edit</button></td></tr>

Then your edit function can accept this argument and use it:

function edit(lineNumber) {
    $.getJSON("editstops.php",{ LineNumber: lineNumber }, stophandler);
}

Note that if your buttons are inside a form tag you might also need to add a return false; after calling edit() to prevent it from submitting the form and refreshing the page.

Simple working example: http://jsbin.com/okesom/2/edit

Alternatively you could leave off the onclick event in your button tag entirely. After your loop is done and the table is built, attach an event to all the buttons like this:

$("button").click(function() {
    var lineNumber = $(this).attr('id');
    $.getJSON("editstops.php",{ LineNumber: lineNumber }, stophandler);
});

Here is a quick example of the second option: http://jsbin.com/ibokon/2/edit

Upvotes: 1

Related Questions