John Wick John Wick -3 years ago 186
HTML Question

Passing javascript variable to another function using onclick

I am trying to pass the id which is

var aid = post.id;


to the message container and when the a onClick is being clicked, the page should alert the aid value. Other records are being displayed properly. However, the problem here is that it is saying aid is undefined. How do i fix this issue?

var message_container = '<div class=\"new-update clearfix\"><div class=\"update-done\"></br> </div> <a onClick="reject('+ aid + ');" id="aid" class=\"tip\" ><i style=\"font-size: 2em; float:right\" class=\"icon-remove\"></i></a> </br></br> </div>';
$.ajax({
url : '/test/back-api/admin/announcements',
method : 'GET',
success : function(d) {
if (d.result) {
var posts = d.data;
for (var i = 0; i < posts.length; i++) {
var post = posts[i];
var aid = post.id;
//message.find('#aid').append("href", post.id);
$("#announcement-container").prepend(message);
}
} else {
$('#announcement-container').append("<div> Nothing to show. </div>");
}
}
});
var reject = function(aid){
$.ajax({
url: app.api + "admin/transaction/remove/"+aid,
type: 'post',
success: function(d){
alert(aid);
}
})

Answer Source
var message_container = $('<div class=\"new-update clearfix\"><div class=\"update-done\"></br> </div> <a onClick="reject('+ aid + ');" id="aid" class=\"tip\" ><i style=\"font-size: 2em; float:right\"  class=\"icon-remove\"></i></a> </br></br> </div>');
$.ajax({
    url : '/test/back-api/admin/announcements',
    method : 'GET',
    success : function(d) {
        if (d.result) {
            var posts = d.data;
            for (var i = 0; i < posts.length; i++) {
                var post = posts[i];
                $(message_container).find('#aid').attr("onClick", "reject('"+ post.id + "')");
                $("#announcement-container").prepend($(message_container).clone(true));
            }
        } else {
            $('#announcement-container').append("<div> Nothing to show. </div>");
        }
    }
});
var reject = function(aid){
     $.ajax({
         url: app.api + "admin/transaction/remove/"+aid,
         type: 'post',
         success: function(d){
           alert(aid);
         }
    });
}

Please see the updated answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download