Access an item of the loop out of the loop - javascript

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?

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
});
});

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"
});
});

Related

jquery add value and text to li of ul elements from json reponse

We want to bind json response to li elements with each element having value as id and text as name.
$.ajax({
type: "GET",
url: "/api/xyz/",
dataType: "json",
success: function(response) {
var items = [];
$.each(response, function(i, item) {
items.push('<li</li>",{value:item.id,text:item.name}');
});
$('#formFieldCity ul').append(items.join(''));
}
});
But no success, I don't see any binding. Can anyone help?
you should write like this:
$.each(data, function(i, item) {
items.push('<li id="'+item.id+'">'+item.name+'</li>');
});
I think you mean
var list = $('#formFieldCity ul'); //caching
$.ajax({
type: "GET",
url: "/api/xyz/",
dataType: "json",
success: function (response) {
var items = [];
//Misplaced variable here: data instead of response
$.each(response, function(i, item) {
var mapped = {value:item.id,text:item.name};
items.push(mapped)
list.append("<li id=\""+item.id+"\">"+item.name+"</li>");
});
}
});
This will basically print a json in your HTML.
Hope I got what you wanted.
EDIT:
If your response is an array, consider using a simple for loop, which is about 8x faster then the jQuery.each
for(var i=0; i<response.length; i++){
var mapped = {value:response[i].id,text:response[i].name};
items.push(mapped)
list.append("<li id=\""+mapped.value+"\">"+mapped.text+"</li>");
}

Jquery, For each looping a List of objects

I have a list of "User" with has Name, Surname and Email.
I need to loop through it on Jquery. This list is returned by a server side method
success: function (result) {
// var res = result.d
$.each(result, function (index, obj) {
alert(obj);
});
}
Does anyone know how it can be done?
Edit: The entire Ajax list:
var param = '{"NameofMap":"' + nofm + '", "VillNum":"' + numberV + '"}';
$.ajax({
url: 'GenerateMap.aspx/AddVill',
type: "POST",
data: param,
dataType: "json",
contentType: "application/json",
error: function (msg)
{ alert("Fails"); },
success: function (result) {
$.each(result, function (index) {
alert("Test");
});
}
});
This is the entire Ajax. It returns a list of Class instances ("User")
It displays "Test" but if I change that with alert(result[index].Name); , it displays just an empty box.
As you haven't provide proper information, still you can give this a try.
If you're getting into the success: and able to get alert, you can try like this:
You can have properties with it's name
--> result.Name
--> result.Surname
--> result.email
So Your code will be like following:
$.each(result, function(index) {
alert(result[index].Name);
.......
});
Or
$.each(result, function(index, item) {
alert(item.Name);
.......
});
This might help!
try
$.each(data,function(i, item){
alert(item.name)
});

Cloning a class and appending the second value in the cloned class

I have an ajax for retrieving names from the database, when the names are more than one, i split them then clone the first class so that i can have the other name(second) in the cloned class. It seems not to work, What am i missing?
$.ajax({
type: "POST",
url: base_url + "c_transfer/viewTransfer/" + transfer_id,
dataType: "json",
success: function (data) {
var all_transferors = data[0]['Transferor_Name'];
var sole_transferors = all_transferors.split(',');
for (transferor_counter = 0; transferor_counter < sole_transferors.length; transferor_counter++) {
if (transferor_counter > 0) {
$('.clone').relCopy({});
$("#transferor_name").val(sole_transferors[transferor_counter]);
} else {
$("#transferor_name").val(sole_transferors[transferor_counter]);
console.log(sole_transferors[transferor_counter]);
}
// console.log(sole_transferors[transferor_counter]);
}
Are you trying to do this?
$("#transferor_name").val(sole_transferors[transferor_counter].val());
You need to use .val() at the end?

jQuery Live() doesn't work

Hi from some reason my live() function doesn't work.
i want to add a mew li element with click functionality by clicking on li element inside the ulAllApps. a new li element created inside the ulMyApps but without the click functionality.
HTML:
<div class="MyApps" >
<ul class="ulMyApps">
<li class="MYLinkTR">app1</li>
</ul>
</div>
<div class="AllApps">
<ul class="ulAllApps">
<li class="IECLinkTR">app1</li>
<li class="IECLinkTR">app2</li>
</ul>
</div>
jQuery code:
$(document).ready(function () {
$(".IECLinkTR").click(function () {
var tmp = $(this).html();
$.ajax({
type: "POST",
url: window.location.href+"/addToMyLinks",
data: "{'app': '" + tmp + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(".ulMyApps").append("<li class=\"MYLinkTR\">"+ tmp +"</li>");
},
error: function (msg) {
alert("You have already have that app");
}
});
});
$(".MYLinkTR").live('click', function () {
var tmp = $(this);
$.ajax({
type: "POST",
url: window.location.href + "/removeFromMyLinks",
data: "{'app': '" + $(this).html() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
tmp.closest('li').remove();
},
error: function (msg) {
}
});
});
});
from some reason the new li element created dynamically dont have the CLICK functionality coming from the Live function......
All I can see is that on your MYLinkTR click function you are trying to remove the tmp.closest('li'). Now looking at the docs I think closest is moving up the DOM looking for the closest next ('li') rather then the one it is on. Are you sure you don't want tmp.remove()?
Perhaps seeing if an alert is thrown first on the click to see if it is firing as you don't do anything on error. Something might be happening here that you are not aware of. The other options is changing LIVE to delegate and attaching this to the ul and see if this fires
$('ul.MyApps').delegate('li', 'click', function(e){
alert('does this at least fire');
});

Problem with fetching Id of the dynamically generated tag using jquery

I have the following function to display the id for click event of tag for which the items are appended dynamically.but when execute the function my alert does not display the id,it pop up saying undefined.please can any one tell where exactly i am going wrong.
This is my function
function getmenu()
{
$.ajax({
type: "POST",
url: "JsonWebService.asmx/GetMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success:
function (results) {
$(results).find("Menu").each(function () {
var Text = $(this).find("Text").text();
var MenuId = $(this).find("MenuId").text();
var dmenu = $("#Menudiv");
dmenu.append("<td id='" + MenuId + "'><ul>" + Text + "</ul></td>");
});
$("#Menudiv").children('td').click(function () {
alert($(this).children('td').attr('MenuId'));
});
}
});
}
This will be my sample xml code generated on ajax call.
<ArrayOfMenu><Menu><MenuId>1</MenuId><Text>Books</Text></Menu><Menu><MenuId>2</MenuId><Text>Cd</Text></Menu><Menu><MenuId>3</MenuId><Text>Calendar</Text></Menu></ArrayOfMenu>
Change this line:
alert($(this).children('td').attr('MenuId'));
to this:
alert($(this).attr('id'));
That shows the td's id. If you intend to inspect the ul within the td -- and note that you have no li elements within the ul -- you can use "children" as you did above, but you'd need to correct your HTML (<ul><li>...) and change the children selector accordingly... or use find()... depends what you're actually trying to do.

Categories