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');
});
Related
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"
});
});
I have created a widget that displays a html template fetched with an ajax request to the server. I want to refresh the template clicking on a <p> element of the template. However when I click on it, it refreshes the template only once, then, if I try to click again, the event does not respond, it does not execute the request again. This is my code, if someone has any idea what I am doing wrong.
/******** Our main function ********/
function main() {
jQuery(document).ready(function ($) {
var widget_url = "/home/widget?callback=MyCallbackFunction"
$.ajax({
url: "/home/widget",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
success: function (data) {
$('#example-widget-container').html(data.html);
$("#panel-sidebar-icon").on("click", function () {
$.ajax({
url: "/home/widget",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
cache: false,
success: function (data) {
$('#example-widget-container').html(data.html);
}
});
});
}
});
});
}
The template example:
<aside>
<p id="panel-sidebar-icon">Click </p>
<ul>
<li>.... </li>
</ul>
</aside>
events attached to DOM elements are lost when you replace the container html, so.
change this
$("#panel-sidebar-icon").on("click", function () {
to this
$("body").on("click", "#panel-sidebar-icon", function () {
maybe because you create a new DOM object so the event goes with the erasure. You should update simple datas on the element or recreate the same component+event associated to it
In my small practice project, I have a dropdown with a delete button:
function getMessages() {
$.ajax({
type: "POST",
url: "/Message/GetMessageMethod",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(data) {
var jsonData = $.parseJSON(data);
var newHtml = "<table style='width: 100%;'class='table-hover'><tr><th>Message</th><th>Date Posted</th><th>Posted by</th></tr>";
for (var i = 0; i < jsonData.length; i++) {
newHtml += "<tr><td>" + jsonData[i].message + "</td><td>" + jsonData[i].date + " - " + jsonData[i].time + "</td><td>" + jsonData[i].name + "</td><td><div class='btn-group'>"+
"<a class='btn dropdown-toggle' data-toggle='dropdown' href='#'> Actions " +
"<span class='caret'></span></a>" +
"<ul class='dropdown-menu' role='menu'>" +
"<li role='presentation'><input type='button' role='menuitem' value='Delete' class='btn btn-danger delMsg'/></li>" +
"</ul></div></td></tr>";
}
newHtml += "<table>";
$('#txfMessage').html(newHtml);
}
});
};
But my delete button is not firing when I click on it... I have a break point in firebug, but its not reaching it...
$('.delMsg').on('click', function () {
$.ajax({
type: "POST",
url: "/Message/DeleteMessage",
contenetType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
data: JSON.stringify({
id: $('#txfMessage').val()
}),
success: function() {
getMessages();
}
});
});
What could be I doing wrong, I've been busy with this since yesterday but couldn't find anything... Help please!
Thank you in advance!
You need to use jQuery event delegation, because you are attempting to attach an event to an element which does not yet exist in the DOM.
Change:
$('.delMsg').on('click', function () {
to:
$(document).on('click', '.delMsg', function () {
Check out this link for more information.
Since the delete button is created AFTER the AJAX call, your "on" method does not attach the event to it. You may use the live method. It will account for elements created after the method is attached.
EDIT: By the way, this depends on the JQuery version. live still works. If you have to use on, use it correctly, like pointed out by Pierre Granger and Jamie Dunstan.
You have to do something like:
$('#txfMessage').html(newHtml);
$('.delMsg').on('click', function () {
$.ajax({
type: "POST",
url: "/Message/DeleteMessage",
contenetType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
data: JSON.stringify({
id: $('#txfMessage').val()
}),
success: function() {
getMessages();
}
});
});
i.e. bind each time you append new html elements, or use event delegation as in the other answers.
When attempting to access the '.box' class of the $container, using (this) inside of the ajax call doesn't work.
$container.on(
"click",
".box",
function(event){
var description;
if($(this)[0].style.width == '70%'){
$(this).find(".resultData").fadeOut('slow');
$(this).css('width', '18%');
}else{
$.ajax({
url:'scripts/php/fetchResultsData.php',
data: {action:value},
type: 'post',
dataType: 'json',
success: function(data){
description = data[0];
$(this).css('width', '70%');
$(this).append("\
<div class='resultData'>\
<div class='resultName'>" + $(this).find("p").html() + "</div>\
<div class='resultDesc'>" + description +"</div>\
</div>");
/*alert($(this).find("p").html());*/
}
})
}
$container.masonry('reload');
}
);
In case it's not clear what I'm trying to do, I'm attempting to change the css of dynamic elements. But for example,
$(this).css('width','70%');
Isn't adjusting the css at all. If I move it outside the ajax,success section, it works, but then I'm unable to get 'description'.
You're close. 'this' in the context you are using it, refers to the ajax request rather than the thing that issued the event. To fix this, store a copy of this before making the ajax request:
}else{
var me = this;
$.ajax({
...
success: function(data){
description = data[0];
$(me).css('width', '70%');
Just add this to your $.ajax call...
context: this,
...and it'll work.
$.ajax({
context: this, // <-- right here
url:'scripts/php/fetchResultsData.php',
data: {action:value},
type: 'post',
dataType: 'json',
success: function(data) { // ...
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.