Problems on .append() and .empty() - javascript

i have the following code that, if the #test button is click, a content will be generated in #currentActivities. There is another #hide button which simple hide the content of #currentActivities. My problem is if the first time i click #test, i can get the content. When i click #hide, the content of #currentActivities can be hidden as expected. However, if i click #test again, the content cannot be generated. I have tried to add $('#currentActivities').empty(); at the beginning, but seems not work. Can anyone help me and point out my problems?
$("#test").click(function() {
$('#currentActivities').empty();
$.ajax({
type: "GET",
dataType: "jsonp",
jsonpCallback: "jsoncallback",
data: {
//some data here
},
url: "http://mydomain.com/check.php?jsoncallback=?",
success: function(data) {
$.each(data, function(index, student) {
$('#currentActivities').append(
'<li><a href="tutor_student_detail.html" data-name="' + data[index].data.NameA + '">' +
'<h4>' + data[index].data.NameA + '</h4>' +
'<p>' + data[index].data.NameA + '</p>' +
'</a></li>');
$("li a").click(function() {
window.localStorage["view"] = $(this).data('name');
window.localStorage["Request"] = "true";
}); //end of li a
});
$('#load2').hide();
$('#filter').show();
$('#currentActivities').listview('refresh');
},
error: function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
});
return false;
});

You need to use delegate event (aka live event). Cause you're working with a dynamically loaded DOM elements.
Something like:
$('body').on('click', '#test', function() {
// all code belong to click handler
});
For more on delegate event binding using .on() see here.
NOTE:
Instead of body user any static-container of all those newly loaded and appended element.
As your question is on jquery mobile so I think for live evnet delegation you can try something like:
$('#test').live('click', function() {
// all codes belong to click hander
});
and another way is :
$(document).delegate('#test', 'click', function() {
// codes
});

Related

The code in the Ajax done method doesn't recognize the code thats already loaded

So I am trying to make a dynamic system where a button changes when you click on another button. For instance, when you click on the button: "12+4", different buttons will appear at another div. I use an append method for that. But when you click on one of the "patroon" buttons, it will not execute the $(".tile").on('click', function). That is because that code is already executed before the ajax call. My code is below:
arr.forEach(function (value, key) {
$("#row2").append('<button class="dikte" data-value="' + key + '">' + value + '</button>')
});
$(".dikte").on('click', function () {
let dataVal = $(this).data('value');
// Code...
$.ajax({
url: "Api/getObjectGroepen.php",
type: 'GET',
beforeSend: function () {
// $(".spinner-border").removeClass("d-none");
},
success: function () {
// $(".spinner-border").addClass("d-none");
}
}).done(function (data) {
$("#row3").html("");
$(arrObjectGroep).each(function (key, value) {
$("#row3").append('<button class="btn tile" data-value="' + value + '">' + JSON.parse(data)[value] + '</button>')
});
});
});
// Tile section
$(".tile").on("click", function (e) {
// Prevents button from executing
e.preventDefault();
// execute code
console.log(123);
});
So the $(".tile") are all the buttons. And $(".dikte") is the "12+4" button.
Hopefully someone understands my problem about what is going on, it's maybe a bit hard to explain, but I can explain further if there are any questions. Is there a clean and simple solution for this? Rather than moving all the code to the done method.
Jquery doesn't know the button's which you appended dynamically, for that your code should be like below, and which will rescan the document to find the element with the class name
$(document).on('click','.tile',function(e){
// code
});

How to add JS event on JSON success with each

My Code-igniter view has AJAX data as follows. DIV article-data contents list of DIVs.(working perfect) Now i want to each DIV as a button and where i put button click event. Where i put following code.
$(".target").click(function () {
});
JS
$(window).load(function() {
$.ajax({
url: '<?php echo base_url(); ?>' + 'main/data',
dataType: "JSON",
type: "POST",
success: function(retdata) {
$.each(retdata, function(i) {
var content = '<div class="target btn-default">' + retdata[i].content + '</div>';
$(".article-data").append(content); //line 23
});
}
});
});
<div class="article-data">
</div>
You should use Event Delegation using .on() delegated-events approach, when generating elements dynamically. You don't need to bind event in success block.
The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
General Syntax
$(document).on('event','selector',callback_function)
In place of document you should use closest static container.
Example
$(function() {
$(".article-data").on('click', ".target", function() {
//Your code
});
})
$(function() {
$(".article-data").on('click', ".target", function() {
//Your code
});
})
$(window).load(function() {
$.ajax({
url: '<?php echo base_url(); ?>' + 'main/data',
dataType: "JSON",
type: "POST",
success: function(retdata) {
$.each(retdata, function(i) {
var content = '<div class="target btn-default">' + retdata[i].content + '</div>';
$(".article-data").append(content); //line 23
});
}
});
});
<div class="article-data">
</div>
A good read Direct and delegated events
Just use event delegation. It will bind the event to items added to DOM even after the document is ready.
$(document).on('click', ".target", function () {
});

Ajax preloader doesn't stop when finished

I'm using AJAX in jQuery and because I want to display notification to the user while loading items I have used ajaxStart() and ajaxComplete().
The problem is when it loads the first time the notification doesn't get removed.
function runAjax(tags, contracts, educations, towns) {
$(document).ajaxStart(function() {
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function() {
$("#wait").css("display", "none");
});
$.ajax({
url: 'http://www.doyleia.com/anazitisi-ergasias?' + tags + '&' + contracts + '&' + educations + '&' + towns,
}).done(function(data) {
// create jquery object from response
var $html = $(data);
//hide within that object
$html.find('.form-for-hide').hide();
$html.find('p.hidden').removeClass('hidden');
// insert the object
$('div.load-jobs').html($html);
});
}
you can see the problem here.

Getting reference to element that invoked inline function with JQuery

I am inserting elements into the DOM populated with some data I retrieved from a web service. I attached an inline click event to call a function when invoked. The problem is I am not getting a reference to the element that invoked that function.
Code that appends the new elements:
$.getJSON("/search?" + $(this).serialize(), function (data) {
if (data != null) {
$.each(data, function (index, video) {
resultItem.append("<li ><a onclick='loadNewVideo(e)' href='play?video=" + video.video_id + "'>" + "<img width='185' src='" + video.defaultImg + "'/>" + "<span class='video_left_title'>" + video.song.song_name + "<h6 class='artist_name'>" + video.artist.artist_name + "</h6></span></a>");
});
}
});
Function:
function loadNewVideo (e) {
e.preventDefault();
alert($(this).attr("href"));
}
Instead of using inline event handlers, you could delegate the clicks on all a to resultItem:
// Call this only once, when resultItem is already in the DOM
// (for example, on a document.ready callback)
resultItem.on('click', 'a', loadNewVideo);
// Proceed with your current code (slightly modified):
function loadNewVideo (e) {
e.preventDefault();
alert($(this).attr("href"));
}
$.getJSON ("/search?" + $(this).serialize(),function (data) {
if (data != null) {
$.each (data,function (index,video) {
resultItem.append("<li ><a href='play?video=" + video.video_id +"'>"
+ "<img width='185' src='"+video.defaultImg +"'/>"
+ "<span class='video_left_title'>"+ video.song.song_name
+ "<h6 class='artist_name'>"+video.artist.artist_name
+ "</h6></span></a>");
});
}
});
Inline onclick handlers don't go through jQuery, which is why you don't have access.
You can either leave those there and change the handler:
function loadNewVideo(e) {
e.preventDefault();
alert($(e.target).attr("href"));
}
Or, and more preferably, don't use the inline handlers. Just give the a elements a class of video (or whatever) and install handlers with jQuery:
...
resultItem.append("<li><a class='video' href=...'")
...
// and elsewhere
$(resultItem).on('click', 'a.video', loadNewVideo);
jQuery's event object allowed me to grab what the documentation calls the 'current DOM element within the event bubbling phase'.
var originatingElement = event.currentTarget;

Block ui when Loading Page

i want to block my ui until values in my drop down not loaded
my js file code is as follows
$(document).ready(function() {
// Load All Toll Plazas
FillInCascadeDropdown({ userType: -1 }, "#ddlTollPlazas", "/Home/GetTollPlazas/" + -1);
}
function FillInCascadeDropdown(map, dropdown, action) {
$(dropdown).empty();
$.blockUI({ message: '<img src="/Content/images/ajax-loader.gif"/>' });
$.post(action, map, function(data) {
$.each(data, function() {
$(dropdown).append("<option value=" + this.Value + ">" + this.Text + "</option>");
});
}, "json");
$.unblockUI();
}
above code not working on page load.
I think you're problem is you are unblocking as soon as you call blockUI. You need to move the unblock call to a "Success" callback function. The concept of Callbacks are a little tricky. Basically this is the code that runs once the post is successful. I'm sure you've seen this page but refer to the jQuery post page to see where you need to put your callback and here to learn more about callbacks if you need to. Good luck!
Here is how it should look:
function FillInCascadeDropdown(map, dropdown, action) {
$(dropdown).empty();
$.blockUI({ message: '<img src="/Content/images/ajax-loader.gif"/>' });
$.post(action, map, function(data) {
$.each(data, function() {
$(dropdown).append("<option value=" + this.Value + ">" + this.Text + "</option>");
});
$.unblockUI();
}, "json");

Categories

Resources