Reputation: 19
So i have a couple of item that iterate through from database using Jquery and for each of them I output a button to select that specific item and when I click on that row's button I want to POST the details to the controller in MVC.
$.each(data, function (i, val) {
var item = $('<div></div>');
item.append('<h2><a>' +val.Name+ '</a></h2>');
item.append('<a id="button">SELECT</a>');
tab.append(item);
});
And I have this function for the button:
$('#myId').on('click', 'a#button', function () {
alert('Name'+val.Name+'');
var item = { Name: val.Name };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{item:" + JSON.stringify(item) + "}",
url: "/Person/GetData"
});
});
If I add the function inside the loop it will iterate as many times as there are items in there. So how can I deal with this in order to send post the name after I press SELECT button?
Upvotes: 0
Views: 54
Reputation: 133403
Use DOM traversal method to get the desired element to extract text to be passed to $.ajax()
As Identifiers in HTML must be unique use CSS class selector to target them
$.each(data, function (i, val) {
var item = $('<div></div>');
item.append('<h2><a>' + val.Name + '</a></h2>');
item.append('<a class="button">SELECT</a>');
tab.append(item);
});
In the event handler, use .prev()
to target the sibling <H2>
element
$('#myId').on('click', 'a.button', function () {
var item = {
Name: $(this).prev('h2').find('a').text()
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: {
item: item
},
url: '@Url.Action("GetData", "Person")' //Note: this will not work in separate JS file
});
});
Upvotes: 1
Reputation: 32354
Move the click to the bottom of the page outside any loop,
change the id to a class item.append('<a class="button">SELECT</a>');
for your click event to select the proper value
$('#myId').on('click', 'a.button', function () {
var val = $(this).prev('h2 a').text();//get the val.Name value
var item = { Name: val};//create a object
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: item,//jquery will take care of the encoding
url: "/Person/GetData"
});
});
Upvotes: 0