Jquery function is executing twice(or the times if i go forward and then back). onLoad of LoginMenu.jsp ,WorkOrder.jsp is loaded in whatever id.
When WorkOrder.jsp loads it then loads the schedule.jsp in schedule tab defined in WorkOrders.jsp
When Schedule.jsp loads it fetches the records and prints in schedule page which consist of two bootstrap dropdown buttons and a link upon which it will take you to another page. onclick of a link present in schedule.jsp it empties the whatever div and load the SubcaseMain.jsp.
Subcasemain.jsp contains the back button upon clicked it empties the whatever div and loads the WorkOrder.jsp.so when i click on link present in schedule.jsp it goes to click(.delete) function present in WorkOrder.jsp twice and load the modal X number of times the function is present.I have checked the div it is emptied.So why the function is executing many times ?
tag is clear after calling empty method ,but its still in memory ,i have checked the firebug script tab in which it is making multiple sources of javascript.Why js is not cleared even after calling the empty method ??
LoginMenu.jsp
<link href="css_harish/demo.css" rel="stylesheet" />
<link href="css_harish/jquery.mmenu.all.css" rel="stylesheet" />
<link href="css_harish/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<link href="css_harish/bootstrap-paper.min.css" rel="stylesheet" />
<script src="js_harish/jquery-2.2.4.min.js"></script>
<script src="js_harish/jquery.mmenu.all.min.js"></script>
<script src="js_harish/bootstrap.min.js"></script>
<script src="js_harish/modernizr.js"></script>
<script src="js_harish/bootbox.min.js"></script>
<script src="js_harish/validator.js"></script>
<script src="js_harish/moment.min.js"></script>
<script src="js_harish/bootstrap-datetimepicker.min.js"></script>
<link href="css_harish/Loader.css" rel="stylesheet" />
<div class="content" id="whatever"></div>
$(document).ready(function () {
$(function () {
$("#whatever").empty();
$("#whatever").load("WorkOrders.jsp");
});
});
WorkOrders.jsp
$(document).ready(function() {
$("#schedule .showbox").show();
$("#schedule").load("Schedule.jsp");
});
$(document).on("click", ".delete", function(e) {
//delete the appointment
e.preventDefault();
alert("delete");
$("#edit_objid").val($(this).data('id'));
var objid = $("#edit_objid").val();
bootbox.confirm({
title: 'Delete Appointment',
message: 'Are you sure you want to delete this Appointment. ?',
buttons: {
'cancel': {
label: 'Cancel',
className: 'btn-default pull-left'
},
'confirm': {
label: 'Delete',
className: 'btn-danger pull-right'
}
},
callback: function(result) {
if (result) {
url="deleteAppointment.action?objid="+objid;
$.ajax({
type: 'POST',
cache: false,
async: true,
url: url,
dataType: 'json',
success: function(data) {
if(typeof data['EXCEPTION']!="undefined"){
bootbox.alert("Exception Occurs while deleting the appointment :"+data.EXCEPTION);
}else{
bootbox.alert("Deleted Successfully.");
$("#containerid").html('');
$("#containerid").html($(".showbox").html());
getSchedule();
}
}
});
}
}
});
});
Schedule.jsp
$(document).on("click", ".opensubcase", function() {
var id_number=$(this).text();
$("#whatever").empty();
$("#whatever").load("SubCaseMain.jsp?id_number="+id_number);
});
SubcaseMain.jsp
<span style="float:left" data-toggle="tooltip" data-placement="right" title="Go Back"><img
style="float: left" class="back" src="back.png" width="35px"
height="35px" /></span>
$(document).on("click", ".back", function() {
$("#whatever").empty();
$("#whatever").load("WorkOrders.jsp");
});
My guess is that you are binding multiple click events for the back button, try using
$(document).one("click", ".back", function() {});
instead
$(document).on("click", ".back", function() {});
example:
$(document).one('click', '#clickOnce', function(){
alert('clicked');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='clickOnce'>click me</button>
This has to do with how the script is parsed and put in the page DOM. Removing the script tag once it has parsed and executed does not remove it.
See this markup and code for example:
Markup:
<div class="wrapper">wrap it up
<button id="howdy">
howdy
</button>
<div id="whatever">
<div class='inside'>insidetop</div>
<script>
$(document).ready(function() {
$('#howdy').on('click', function() {
console.log('howdyclick from org');
})
});
</script>
<div class='inside'>inside</div>
</div>
<button id="test">
test
</button>
</div>
Code:(not in the markup)
console.clear();
var testthing = "<scr"+"ipt>$(document).ready(function(){$('#howdy').on('click', function(){console.log('howdyclick from test');});});</scr"+"ipt> <div class='inside'>inside</div>";
$(document).ready(function() {
$('#howdy').on('click', function() {
console.log('howdyclick from outside');
})
});
$('#test').on('click', function() {
$('#whatever').empty();
$('#whatever').html(testthing);
});
Now when you execute this, you can click the "howdy" button. you get the first line of this in console, note that the second line is from the outside handler.
howdyclick from org
howdyclick from outside
Now click the "test" button which puts NEW script and markup as you have done.
Now click the "howdy" button again - see you STILL get the response from the original code inside the "whatever" which now has new markup and script - which then adds the THIRD line. So you see the original still exists and executes.
howdyclick from org
howdyclick from outside
howdyclick from test
I put a fiddle together so you could see for for yourself here https://jsfiddle.net/8fwfoc5b/
Related
I am attempting to click a button dynamically using javascript to call a js function, when I launch the page, the javascript function is never called by the button to be clicked dynamically. here is my snippet
<button id="deSubmit" type="submit" >
To be clicked automatically
</button>
<script type="text/javascript">
document.getElementById("deSubmit").click();
</script>
Here is the js function I want to be called dynamically
$("#deSubmit").click(function () {
$(function () {
url_redirect({
url: "${url}",
method: "post"
});
});
........
Please what could be wrong
Call it in document.ready
$("#deSubmit").click(function () {
console.log("teste")
/*$(function () {
url_redirect({
url: "${url}",
method: "post"
});
});*/
});
$( document ).ready(function() {
document.getElementById("deSubmit").click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="deSubmit" type="submit" >To be clicked automatically</button>
Attach click event inside document.ready. Also $(function () { this wrapper is not required
$(document).ready(function() {
document.getElementById("deSubmit").click();
})
$("#deSubmit").click(function() {
console.log('test')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="deSubmit" type="submit">To be clicked automatically</button>
I don't know why you want to click a button, you can write this function on load of script as well.
You need to enclose your code inside the document ready function to make sure your document loads before any JavaScript code is executed.
And for simplicity purpose, I have invoked click event using JQuery onlu.
$(document).ready(function() {
$("#deSubmit").click(function() {
/* url_redirect({
url: "${url}",
method: "post"
});
*/
alert('function called');
});
$('#deSubmit').click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button id="deSubmit" type="submit">
To be clicked automatically
</button>
Don't complicate with jQuery and Javascript.
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
const btn = document.getElementById("deSubmit");
btn.addEventListener("click", function() {
alert("here2")
});
btn.click();
});
</script>
Use above code this will work.. just put your code in place of the alert.
I have a website with a link. When I click the link I want a smooth page transition to the next page using jQuery. I got the the HTML elements inside the barba DOM to fade out. But when the next page tries to load, all BUT the JavaScript loads.
This is my code:
(index.html)
<div id="barba-wrapper" class="wrapper">
<div class="barba-container">
<div class="container">
<span class="text1">Hey There!</span>
<span class="text2">This is my portfolio!</span>
<a id="homeLink" href="./home.html">Click me to continue</a>
</div>
</div>
</div>
<script>
$('document').ready(function(){
var transEffect = Barba.BaseTransition.extend({
start: function(){
this.newContainerLoading.then(val => this.fadeInNewcontent($(this.newContainer)));
},
fadeInNewcontent: function(nc) {
nc.hide();
console.log('stuff should be hidden');
var $el = $(this.newContainer);
var _this = this;
$(this.oldContainer).fadeOut(1000).promise().done(() => {
nc.css('visibility', 'visible');
nc.fadeIn(1000, function(){
console.log('new content should fade in.');
_this.done();
})
});
}
});
Barba.Pjax.getTransition = function() {
return transEffect;
}
Barba.Pjax.start();
});
</script>
I can see the the console logs in the console but JavaScript doesn't load.
This is the page I'm trying to load:
(home.html)
<div id="barba-wrapper" class="wrapper">
<div class="barba-container">
<canvas></canvas>
<script src="canvas.js"></script>
</div>
</div>
I get no errors whatsoever.
Also I have seen a question on here with the same problem as mine, but it was very unclear. (and does not have any answers so far)
Thanks!
In Barba, scripts don't evaluated when loading a new container. It can be done easily using Events.
Barba.Dispatcher.on('newPageReady', function (currentStatus, oldStatus, container) {
$(container).find('script').each(function (i, script) {
var $script = $(script);
$.ajax({
url: $script.attr('src'),
cache: true,
dataType: 'script',
success: function () {
$script.trigger('load');
}
});
});
});
Add this line:
document.getElementsByTagName("head")[0].innerHTML += "<meta http-equiv=\"refresh\" content=\"1\">";
inside below function
fadeInNewcontent: function(nc) {
}
I have the following in a event:
function onclickEvent () {
$.ajax({
url: "somePage.html",
beforeSend: function( xhr ) {
$('#Element1').hide("slow",function() {
$('#Loading').show("slow");
});
}
}).done(function( data ) {
$('#Loading').hide("slow",function() {
$('#Element1').show("slow");
});
});
}
First time works well but the second time (second click) in "Done" ajax the loading does not hide, always is visible.
What am I doing wrong?
You hid Element1 first, so you need to show it first on success/done. show() paired with hide() and vice versa seem to base the toggling on precedence. It seems to be the behavior. You may want to further read the documentation of these functions.
<script src="jquery.min.js"></script>
<script>
function onclickEvent () {
$.ajax({
url: "somePage.html",
beforeSend: function( xhr ) {
$('#Element1').hide("slow",function() {
$('#Loading').show("slow");
});
}
}).done(function( data ) {
$('#Element1').show("slow", function() {
$('#Loading').hide("slow");
});
});
};
</script>
<div id="Element1" style="display:block;">
Element 1
</div>
<div id="Loading" style="display:none;">
Loading
</div>
<button onclick="onclickEvent();">Click Me</button>
Using success
function onclickEvent () {
$.ajax({
url: "somePage.html",
beforeSend: function( xhr ) {
$('#Element1').hide("slow",function() {
$('#Loading').show("slow");
});
},
success: function( data ) {
$('#Element1').show("slow", function() {
$('#Loading').hide("slow");
});
}
});
};
It looks like there are couple of things that need to be modified to get this to work the way I think you want it to work.
The beforeSend setting in the $.ajax() function is intended to give you a place to modify the request before you send it. This probably isn't the best place to call the first animation functions.
The animation callbacks and ajax callbacks seem to be causing a race condition -- it looks like it's possible for the ajax request to return while the initial animations are still running, which means that the #Loading element is shown when it should be hidden.
This example assumes that the #Loading element should be hidden by default when the page loads and that the elements should revert to their initial state even when the ajax request fails (always instead of done).
$(function() {
$('#button').on('click', function() {
$('#Element1').hide('slow', function() {
$('#Loading').show('slow', function() {
$.ajax({
url: 'somePage.html'
})
.always(function(data) {
$('#Loading').hide('slow', function() {
$('#Element1').show('slow');
});
});
});
});
})
})
#Loading {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="Element1">
Element1
</div>
<div id="Loading">
Loading
</div>
<button id="button">
Button
</button>
What's happening here is that when the button is clicked, the toggling animations (hide() and show()) are run, then the ajax request is sent as a callback from the show() animation so that the request doesn't go out until the #Loading element is visible.
I am trying to load a page into a which is triggered by a click. Works fine without using click event or funtion, but if I add a some of that it doesn't work. I looked into some examples but a can't figure this out. Code:
$(document).ready(function () {
$('#LoadByActivities').on('click', function () {
$.ajax({
url: 'ByActivities.aspx',
dataType: 'html',
success: function (data) {
$('#TableContainer').html($(data).children('#todayActivitiesFor'));
}
});
});
});
HTML Loaded
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="../styles/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form runat="server">
<div id="todayActivitiesFor">
SOME TEXT
</div>
</form>
</body>
</html>
HTML where it is received
<body>
<form id="todayActivitiesForm" runat="server">
<div>
<asp:TextBox ID="dia" runat="server" TextMode="Date"></asp:TextBox>
<asp:Button Text="Enviar" ID="submit" runat="server" OnCommand="submitDate"/>
<button id="LoadByActivities">Por Actividades</button><br />
<div id="TableContainer"><asp:Table runat="server" ID="todayActivitiesTable"></asp:Table></div>
</div>
</form>
</body>
Once the entire page was shown it is obvious (and also one of the most common mistakes). The code precedes the elements it references.
You also need to stop the button from submitting the form as it is probably refreshing the page. Use e.preventdefault() for that.
With jQuery, you either have to place the code after the elements it references, or you need to wrap it in a DOM ready event handler. This will delay execution until all DOM elements have been loaded.
What is happening at the moment is $('#LoadByActivities') matches nothing because that element is still being loaded after the code has been run (the code gets run as it is found in the page).
Add a DOM ready handler:
<script type="text/javascript">
$(function(){
$('#LoadByActivities').click(function (e) {
// Stop the form submitting
e.preventDefault();
$.ajax({
url: 'ByActivities.aspx',
dataType: 'html',
success: function (data) {
alert("Ajax2");
$('#TableContainer').html($(data).find('#todayActivitiesFor'));
},
error: function (data) {
alert("Ajax3");
}
});
});
});
</script>
Note: $(function(){ YOUR CODE }); is just a handy shortcut for $(document).ready(function(){ YOUR CODE });
Another alternative to DOM ready is to use a delegated event handler, attached to document (which is always present). The jQuery selector is only run at event time (not when the event is registered) so can work with elements that do not exist yet. This is a bit more advanced though.
<script type="text/javascript">
$(document).on('click', '#LoadByActivities', function (e) {
e.preventDefault();
$.ajax({
url: 'ByActivities.aspx',
dataType: 'html',
success: function (data) {
alert("Ajax2");
$('#TableContainer').html($(data).find('#todayActivitiesFor'));
},
error: function (data) {
alert("Ajax3");
}
});
});
</script>
You can replace the entire ajax call with load() (as load allows a selector expression after the url):
e.g.
<script type="text/javascript">
$(function(){
$('#LoadByActivities').click(function (e) {
e.preventDefault();
$('#TableContainer').load('ByActivities.aspx #todayActivitiesFor');
});
});
</script>
the error "Uncaught ReferenceError: answers is not defined" The problem is that i thought i defined the variable.
summary of my code.
I have a class that turns on, on click, then another function that maps those answers and puts it into the array answers.
im then using ajax to send the name entered into the form and the array i just made to a php doc. the array is the part thats giving me trouble
live version on the site
Jsfiddle
$(document).ready(function() {
//catch this values, because you will use these for more than one time
var answers = [];
function getAnswers() {
answers = []; //empty old answers so you can update it
$.map($('.on'), function(item) {
answers.push($(item).data('value'));
});
}
//init the answers in case you use it before click
getAnswers();
$(document).on('click', 'img', function(e) {
e.preventDefault();
$(this).toggleClass('on');
//trigger the state change when you click on an image
$(document).trigger('state-change');
});
//get answers when event was triggered
$(document).on('state-change', function(e) {
getAnswers();
});
$('#btn-show').click(function() {
alert(answers.join(',') || 'nothing was selected');
});
});
//ajax to send the data to php file
$(document).on('click', '#btn-show', function() {
$.ajax({
type: "POST",
url: ".../inc/insert.php", //"/path/to/script.php"
data: {
"name": $('input[name="name"]').val(),
"choices": answers
//this is the part giving me an error
},
success: function(response) {
alert(response);
//the response variable contains whatever your PHP echoes out --
}
});
});
/* style for the selectable images */
.choices {
margin: 8px;
font-size: 16px;
height: 100px;
width: 100px;
}
/* this shows the user which item has been selecting along with making a searchable class for the program */
.on {
padding: 10px;
background-color: red;
}
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/javascript.js"></script>
<LINK REL=StyleSheet HREF="css/code.css" TYPE="text/css">
<!DOCTYPE HTML>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/javascript.js"></script>
<LINK REL=StyleSheet HREF="css/code.css" TYPE="text/css">
</head>
<body>
<form method="post">
Name
<input type="text" name="name" />
<br>
<img src="img/m_bacon.jpg" alt="Bacon" class="choices" data-value="0">
<br>
<img src="img/m_beef.jpg" alt="Beef" class="choices" data-value="1">
<br>
<button id="btn-show">Submit</button>
</body>
</html>
You have a scope issue. Notice that you declare var answers = [] in the $(document).ready(function () {...} function, but your click event is outside that ready function.
Also here is the edited version of your fiddle: http://jsfiddle.net/ku9pwo4c/1/ (Note that it won't work on JS Fiddle due to the AJAX request url, but if you paste it, it should work assuming your PHP endpoint works correctly.)
Here is a a simplified example:
$(document).ready(function () {
var answers = [];
});
$(document).on('click', '#btn-show', function () {
// This will be undefined because answers was declared in a
// different function scope.
console.log(answers);
});
A possible fix is to move your click event handler inside the ready function:
$(document).ready(function () {
var answers = [];
$(document).on('click', '#btn-show', function () {
// This time answers will be `[]`
console.log(answers);
});
});
I also added a snippet of the working example:
$(document).ready(function () {
var answers = [1, 2, 3, 4];
$(document).on('click', '#btn-show', function () {
console.log(answers);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="btn-show">Click me!</button>