Why is my jQuery click function not firing? - javascript

I am building a search page that posts back to itself. I finally got a sample page working here. I also built a fiddle here. But I don't understand why it works. When the user initially hits the page, it should only show the search form. When a search is submitted, it should hide the form, show results, and a button for a new search. I'm using jQuery. Here's my code:
//Code Block 1
// Show search form if there is no querystring
//Hide search form, show results if querystring
$(document).ready(function() {
if(document.location.search.length) {
$("#newsearch").show(1000);
$("#results").show(1000);
$("#search").hide(300);
} else {
$("#search").show();
}
});
//code block 2
//if new search clicked, show form, hide results
$("#newsearch").click(function() {
$("#newsearch").hide(1000);
$("#results").hide(1000);
$("#search").show(300);
});
When code block 1 and 2 are loaded in the head, block 2 never fires. When I pull 2 out and put it at the end of the page, it works.
I am trying to learn, so I have 2 questions. (1) Why didn't it work when it was one block, and (2) Any suggestions for doing it better?
Thank you.
D

$("#newsearch").click(function() { is being run before the #newsearch element exists.
Therefore the click event is attached to nothing.
It works in the first block because it's in a $(document).ready, which runs code inside only after everything has finished loading.

Related

How to fix: Ajax - Post request running multiple times

I have a table (formatted with Datatables script) and it has a column which contain few icons to manage actions. When user click on an icon, it load a modal and get the modal content using POST method.
Modal has a save button to complete the action after user make their choice. When they click save button, another post script complete the request and feedback to user.
This process working fine when the first time user load the page. There is a refresh button on the page which can reload the TABLE without reload the PAGE.
If user use this button to refresh the page and try above action. it open the modal and Save button trigger the post action 2 times. If the user refresh the page (using the refresh button) again and try one of the action icons, post script run 3 times... in other words if you refresh 10 times post script run 10 times...
if user use the browser refresh button, we don't get this repetition.
Just wondering whether we can fix this without get rid of the refresh button.
We tried different ways to place the script within the page. but still cannot understand what is triggering the multiple post request.
//javascript
//step 1 - load the modal with an action list
$("#proj_data tbody").on("click", ".update_job_progress", function () {
var pn = $(this).attr('mypn');
$.post('reports_job_progress.php', {proj: pn}, function (data) {
$('<div id="progress_update_modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true"></div>').appendTo('#modal-container').html(data).modal();
});
});
//step 2 - save user choice
$('body #modal-container').on('click', '.btn_jobaction', function () {
var pn = $("#pn").val();
$.post("reports_job_progress_backend.php", $("#progress_list").serialize(),
function (res) {
if (res === 0) {
alert("There is a problem saving the information. please try again");
} else {
$("#prog" + pn).html(res);
$("#progress_update_modal").modal('hide');
}
}
);
});
//step 3 - destroy the modal
$("body").on("hidden.bs.modal", ".modal", function () {
$("#modal-container").empty();
});
Could you please help me to understand the issue with this code?
It looks like your problem is being caused by binding multiple onclick handlers to the element. Please try using off like this $("#proj_data tbody").off("click").on("click", ... and see if that fixes your issue.
#buffy solution worked. However just adding .off('click') was disabling other icons click event as all icons share the same class. after playing with the code i found adding $(this).off('click') does the trick. Now everything working perfect. Thanks #buffy for providing correct directions.
You will bind the click event multiple times. You could either reset the callback, check if the callback has been set or (much better) set the click listener in a part of your script, that will not be executed, whenever you refresh your page (with the mentioned refresh button) like:
$(document).ready(function() {
$('body #modal-container').on('click', ...
$('body #modal-container').on('click', ...
});

Can we remove click event without calling it?

I am having problem in overriding the pagination code given by grid. What I need to do is kind of hack the pagination given by my grid.
We are having a lot of records. So, what we are doing we are loading records to a threshold limit.
So, lets assume the threshold limit is 50 and page size is 10 so there will be 5 pages. So, when user comes to 5th page next button provided by the grid will be disabled.
So, what we need to do we need to make it enable and if user clicks on it I need make ajax call and load another 50 records(threshold limit) in the grid.
After that I need to disable this event so that next time user clicks it should not do the make ajax call and it should work like previously (by going from 1st page to 2nd page and so on)
All the above things mentioned I am able to do. But here problem comes when user goes to 5th page and go back to some other page let say 3 without clicking next button. Now, after going to 3rd page
when user clicks on the next page button it is making ajax call as I have make the button enable when user comes to 5th page and provided a click event to it.
So even if I provide a condition to run only on when grid current page is 5 then also it is running because after going to 5th page I will make button enable and bind and event. So, as I provided the event it will run without even specifying the condition.
How do I make the click event work as default and only when the user is at 5 it will make the ajax call.
This is my code -
///grid Current page will tell us which page we are in the grid.
if(gridCurrentPage==5){
query(".dojoxGridWardButton").forEach(function(element) {
query(".dojoxGridnextPageBtnDisable").replaceClass("dojoxGridnextPageBtn", "dojoxGridnextPageBtnDisable");
query(".dojoxGridlastPageBtnDisable").replaceClass("dojoxGridlastPageBtn", "dojoxGridlastPageBtnDisable");
});
callNextButton(gridCurrentPage)
}
And this is the function.
function callNextButton(gridCurrentPage) {
var target = dojo.query(".dojoxGridnextPageBtn");
var signal = on(target, "click", function(event){ ///Adding click event
if (gridCurrentPage ==5 ) {
var deferred = new dojo.Deferred();
setTimeout(function() {
deferred.callback({
called: true
})
}, 2000);
if (checking some conditions) {
////////doing Ajax call
deferred.then(function() {
//calling a callback
})
},
error: function(e) {}
};
})
signal.remove(); //Removing click event
}
Note : My grid is enhanced grid which is part of dojo toolkit. But probably its a design issue so, any comments/advices are welcome.
I really need an advice here. Please anyone can find the problem where it is it will be reqlly helpful.

Obstructed JavaScript code: part of codes are not executed starting from second click

What I want is to trigger a Bootstrap modal (with an Id testModal) by a button click and update its content dynamically. Be more precise, I want to check if a certain div tag has been created, if yes then remove it and create a new one. For this I came up with the following jQuery code for testing purpose:
jQuery('#testModalButton').on('click',
function(){
'use strict';
jQuery('#testModalTitle').html('Country list');
console.log('Check if a div exists');
//...other codes...//
var $testModalBodyDiv = null;
if (jQuery('#testModalBodyDiv').length != 0) {
// if yes, then remove it.
jQuery('#testModalBodyDiv').remove();
}
else {
$testModalBodyDiv
= jQuery("#testModalBody")
.append($('<div id="testModalBodyDiv">'));
}
// end of...other codes...//
jQuery('#testModal').modal('show');
}
);
What bugs me is that, after the first click, everything runs fine, [...other codes...] is executed and modal is opened too. However, when I click the button again, the modal can be opened, yet the [...other codes...] part is not executed at all. At the third click, it runs fine again. This pattern repeats. I am wondering what went wrong.
NOTE ADDED: Well, my stupidity comes from a misuse of
$testModalBodyDiv = jQuery("#testModalBody").append($('<div id="testModalBodyDiv">'));
which, as a matter of fact, first selected the testModalBody instead of testModalBodyDiv in my previous codes.

page reloads on changing the radio buttons

I'm working on a checkout process on a site. i wrote a piece of code to handle the steps, using java script and session storage. session storage keeps the current step. i wrote a function to stay on the same step on reloading the page.
it works fine, but there is two radio buttons on one of steps that user can choose the payment method using them. when user chooses one of them, page reloads but the function doesn't get called. :/ this is the function:
jQuery(document).ready(function() {
if (sessionStorage.checkoutstepHolder > 0) {
cartButtonHandler("onLoad");
}
});
the question is, why the function gets called on reloads caused by refreshing, but not on reloads caused by choosing the radio buttons?
maybe the radio button doesn't reload the page, maybe its doing something else :/
I would use a seperate function for this, because you use it on multiple occasions.
jQuery(document).ready(function() {
ReloadFunction();
});
function ReloadFunction() {
if (sessionStorage.checkoutstepHolder > 0) {
cartButtonHandler("onLoad");
}
}
On radiobutton change:
jQuery(document).on('change', '#radiobuttonID', function(){
ReloadFunction();
});

refresh div (populated by jquery) when form (inside div) is submitted

Here is my scenario. I have a 'Master Page (Course_Maintenance.php)' that has 2 divs on it. The first is populated from the code on Course_Maintenace.php. The second div populates using the following:
$(document).ready(function() {
$("select[id='SelectCourse']").change(function() {
var link = 'CourseTeeInfo.php?CourseID='+$(this).val();
$('#CourseTeeInfo').load(link);
})
});
The CourseTeeInfo.php page has a form that populates and works perfectly. I use a staging system on that page:
// Get stage of form
if(!isset($_POST['btn_submit']) || !$_POST['btn_submit']) { $stage=0; }
if(isset($_POST['btn_submit']) && $_POST['btn_submit'] == 'submit') { $stage=1; }
So once the form is filled out and validated, I use javascript to change the value of btn_submit to come back to the form to use PHP to write to the MySQL database:
function ValidateForm() {
if(!noErrors2()) { alert("You must fix errors on page before submitting"); }
document.getElementById('btn_submit').value = "submit";
document.TeeInfo.submit();
}
Currently I have Stage 2 just echoing the $_POST variable to the screen. This all works if I call CourseTeeInfo.php directly. However, when I click the Update button on the form (which fires the ValidateForm() javascript) within the div on Course_Maintenace - the div refreshes to a blank screen rather than the $_POST variable display (as it does running directly).
Any insight on how to have the div refresh properly in the parent (Course_Maintenace.php) window would be greatly appreciated. I simply want the div to work exactly like the form works if called directly. My goal is that after I successfully write the record (in $stage=1) that I will reload the form (yet again) back to $stage=0 which will then have the new/updated information.
Thanks in advance for the help.
I changed the approach slightly and used jQuery AJAX calls to write to the MySQL database (instead of reloading the form). After writing the record, I simply refreshed the div using the jQuery .load function.

Categories