not firing event in jquery - javascript

I have a list that page load, loads items. and when click checkbox in page load items with json.
$('.content-items:checkbox').on('change',
function () {
$.get(newUrl, function (data) {
$("#ProductsPartialView").empty();
$("#ProductsPartialView").append(data);
$('#loadingModal').modal('hide');
}).fail(function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});
when click items element run a function.
$('.compare-items:checkbox').on('change',
function() {
$('#loadingModal').modal('show');
var value = $(this).data('id');
$.getJSON("/store/AddToCompare", {
id: value, add: true
}, function (result) {
$(".compare-footer").show();
$(".compare-count").html(result);
$('#loadingModal').modal('hide');
});
}
});
when load items in page load, fire this jquery, but when load items with json in first code, don't fire second function.

for that you need $(document).on(event,selector, cb{}); when you want to do action on dynamic generated data
$(document).on('change','.compare-items:checkbox',
function() {...

Related

jquerymobile. double execute function

I have such code:
function getData(){
$.ajax({
url: 'http://pechati.ru/extdata/baseparts/filialsWSunsec.php',
contentType: "application/x-www-form-urlencoded;charset=utf8",
dataType: 'json',
success: function(jsonData){
//alert('Load was performed.');
console.debug('Data received.');
//jsonData = win2unicode(jsonData);
console.debug(jsonData);
$.each(jsonData,function (filial,dataFilial) {
//
//console.debug(filial);
var option = '<option value="'+filial+'" data-phone="'+ dataFilial.phone+ '" data-email="' + dataFilial.email + '"> ' + filial + '</option>';
//filial active
var activeFilial = 0;
if (parseInt(dataFilial.mainList)>0){
activeFilial++;
}
if (parseInt(dataFilial.contacts)>0){
activeFilial++;
}
if (parseInt(dataFilial.uslugi)>0){
activeFilial++;
}
if (activeFilial>0){
$('#filial-name').append(option);
}
});
},
error: function(error){
console.debug('We have a problem: ');
}
});
}
...
$(document).bind('pageinit', function() {
$('a.get-order').on('click', function () {
getData();
});
}
getData is executing twice after click on a.get-order it. Why is happening it?
This is element placed in :
<div id="one">
...
</div>
<div id="two">
...
<a class="get-order">...</a>
</div>
The first page is loaded "#one". From it called page "#two". After click on a.get-order I have double execution getData(). If I am calling page "#three" from page "#two" and execute some function there it executed three times.
Why is it happening and how fix it?
Your code:
$(document).bind('pageinit', function() {
$('a.get-order').on('click', function () {
getData();
});
}
Runs every time any page is initialized. So the click handler is added once when #one is initialized and then again when #two is initialized. Change it to
$(document).on("pageinit","#two", function(){
$('a.get-order').on('click', function () {
getData();
});
});
This way the click handler is only added once when page #two is initialized.

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.

Problems on .append() and .empty()

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

jQuery change event returns null when manually fired on $(document).ready();

I'm currently writing a JQuery plugin that loads colors from a JSON web service into a drop down list.
The drop down list background-color changes according to the selected value. For the most part it is working. on any regular change it works as expected, the problem I am having is on the initial page load I am using triggerHandler("change"); and it triggers but I seem to be getting an undefined error on the selected value from the drop down list on page load so it doesn't trigger the color change on the drop down list
My code is:
$.fn.bindColorsList = function (options) {
var defColor = options.defaultColor;
var svcUrl = options.svcurl;
//var f_target = options.filterTarget;
var $this = this;
$.ajax({
url: options.svcurl,
dataType: 'json',
/*data: { filter: src_filt },*/
success: function (fonts) { fillcolors(fonts, $this) },
error: function () { appendError(f_target, "colors failed to load from server") }
});
this.on("change", function (event) {
log($(event.target).attr("id") + " change detected");
//change ddl dropdown color to reflect selected item ;
var hcolor = $this.find('option:selected').attr("name");
$this.attr("style", "background-color:" + hcolor);
});
function fillcolors(colors, target) {
$(target).empty();
$.each(colors, function (i, color) {
$(target).append("<option name='"+color.HexValue+"' value='" + color.Name + "' style='background-color:"+color.HexValue+"'>"+color.Name+"</option>");
});
};
//in a seperate file
$(document).ready(function () {
$("#dd-font-color").bindColorsList({ svcurl: "/home/colors"});
$("#dd-back-color").bindColorsList({ svcurl: "/home/colors" });
});
You are doing an AJAX request to populate your dropdown which, by the way, is an asynchronous one. In this case you need to trigger the event in the success callback of the AJAX request.
var $this = this;
// Bind the onchange event
$this.on("change", function (event) {
..
});
// Populate using AJAX
$.ajax({
...
success: function (fonts) {
// Populate the values
fillcolors(fonts, $this);
// Trigger the event
$this.trigger("change");
},
...
});
That's it.

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