B. Hurray B. Hurray - 2 months ago 5
Javascript Question

Javascript onclick fires without click using it in loop

I'm using AJAX to get one of my database tables. I'm trying to improve it by making an update table function after the button is pressed.

success: function(result) {
for( var i = 0; i < result.length; i++ ) {
document.getElementById('tableT').innerHTML +=
"<tr>" +
"<td>"+result[i]['id']+"</td>" +
"<td>"+result[i]['terminalId']+"</td>" +
"<td>"+result[i]['departmentId']+"</td>" +
"<td>"+result[i]['profileId']+"</td>" +
"<td>"+result[i]['created']+"</td>" +
"<td>"+result[i]['modified']+"</td>"+
"<td>"+"<div style='margin-bottom:10px; text-align: center;'>"+
"<a class='btn btn-info edit-btn' data-toggle='modal' onclick='"+updApplication(result[i]['id'])+"' data-target='#myModal-44' title='Edit'><i class='fa fa-edit'></i></a>"+
"</div>"+"</td>"+
"</tr>";

}
},


Why do I get alerts with all my ids without even pressing a button?

function updApplication(id){
alert(id);
};

Answer

You have a problem in quotes, now you're calling updApplication() function in every loop iteration, your code should be like :

..data-toggle='modal' onclick='updApplication("+result[i]['id']+")' data-target='#myModa..

Hope this helps.

Comments