In my case, I have a parent div which have multiple child div. These child div are generated according to $.each() function.
Number of times function run, num of div get generated.These child div contains data like-- UserId, UserName, UserPic and a follow button.Now, i want to write a server side function on button click and post the UserId to controller.
Now, i have seen many so questions and solution was to have a global variable and assign value to that variable from your $.each function.But, in my case, my $.each function will loop several times so how to get back particular item.Id when a follow button is clicked and post back that value to controller
$(document).ready(function() {
var parent = $(".div1");
$.getJSON("/Home/GetUsers", null, function(data) {
parent.html("");
$.each(data, function(i, item) {
var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>";
html += "<button type='button' class='newButton'>Click Me!</button>";
// wants to send current userId on button click
html += item.Id;
html += "</div>";
parent.append(html);
});
});
parent.on('click', '.newButton', function(e) {
var button = $(this);
var html = "<div class='listItem'>";
$.ajax({
type: "POST",
url: "Home/Follow", // Controller/View
data: { //Here, i am struck, how to get back correct userid from above $.each function
id: $(".listItem").
}
});
});