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>
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've wanted to attach click event to an object not yet added to the DOM like here.
I've used a code from the answer but nothing happens when I click anything.
Here's my HTML:
<html>
<head>
<script src="resources/js/components/jquery/jquery-3.1.1.min.js"></script>
<script src="file.js"></script>
</head>
<body>
asl;kdfjl
<div id="my-button">sdgdf</div>
</body>
</html>
JavaScripts are in those location and I can see them in Sources tab in Chrome.
My file.js has content exactly copy-pasted from jsfiddle:
$('body').on('click','a',function(e){
e.preventDefault();
createMyButton();
});
createMyButton = function(data) {
$('a').after('<div id="my-button">test</div>');
};
$('body').on('click','#my-button',function (e) {
alert("yeahhhh!!! but this doesn't work for me :(");
});
As your code is in the head tag, you need to use a DOM ready wrapper to ensure your code executes after the DOM has rendered elements.
The jsfiddle doesn't have it because the fiddle is set to run the code onload already.
$(function(){
$('body').on('click','a',function(e){
e.preventDefault();
createMyButton();
});
createMyButton = function(data) {
$('a').after('<div id="my-button">test</div>');
};
$('body').on('click','#my-button',function (e) {
alert("yeahhhh!!! but this doesn't work for me :(");
});
});
Your code working with snippet .Better use with document.ready.Post you js after document.ready .And change the selector document instead of body
$(document).ready(function() {
$(document).on('click', 'a', function(e) {
e.preventDefault();
createMyButton();
});
createMyButton = function(data) {
$('a').after('<div id="my-button">test</div>');
};
$(document).on('click', '#my-button', function(e) {
alert("yeahhhh!!! but this doesn't work for me :(");
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
asl;kdfjl
<div id="my-button">sdgdf</div>
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/
I'm trying to write a generic javascript script to facilitate clicking through <a href> links while only replacing the inner HTML instead of reloading the whole page. The strange thing is, it works, except on any link inside of freshly loaded HTML.
<script src="{{ asset('bundles/app/js/jquery-2.2.0.min.js') }}"></script>
<script src="{{ asset('bundles/app/js/jquery.menu-aim.js') }}"></script>
<script src="{{ asset('bundles/app/js/main.js') }}"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").on("click", function(){
event.preventDefault();
$.ajax({
'url': $(this).attr('href'),
type: "post",
success: function(response, status) {
document.getElementById("content").innerHTML = response;
},
error: function() {
console.log('failure');
}
});
});
});
</script>
When I place the exact same URL from the loaded HTML directly in the sidebar menu containing the initial links, it loads fine. According to the documentation, the .on function should attach itself to any elements added later. I've also tried .delegate and the deprecated .live as suggested by older answers but then even the menu sidebar stopped working.
What am I missing here?
Here I assume your link container is "content" by ID, if not fix that with the correct container ID OR even wrap them IN one:
$(document).ready(function() {
$('#content').on('click', 'a', function() {
event.preventDefault();
$.ajax({
'url': $(this).attr('href'),
type: "post"
}).done(function(response, status) {
document.getElementById("content").innerHTML = response;
}).fail(function() {
console.log('failure');
});
});
});
Example markup:
<div id="content">
clickme
</div>
This is NOT as desirable, (placing it on the document) place the handler on the container
if you can
$(document).ready(function() {
$(document).on('click', 'a', function() {
event.preventDefault();
$.ajax({
'url': $(this).attr('href'),
type: "post"
}).done(function(response, status) {
document.getElementById("content").innerHTML = response;
}).fail(function() {
console.log('failure');
});
});
});
As to WHY this is not desirable (the document); you want to place your event handler hooks as close to the element as possible; when you attach to the document as here, if forces the code to go through the entire document for the event handler to find the a links and look for clicks on those.
Note the the documentation says
"A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element."
Thus for the a selector in your case. SO it places the event handler on EVERYTHING in the document, THEN filters on the a selector for yours. SO if you place it on a smaller container, it has to filter less on every event (click) that is executed.
You have to apply the behaviour to the loaded HTML as well, like in this example (not tested):
$(document).ready(function() {
function addBehaviour() {
// .off first so existing behaviour will be removed and not applied multiple times
$("a").off("click").on("click", function(){
event.preventDefault();
$.ajax({
'url': $(this).attr('href'),
type: "post",
success: function(response, status) {
document.getElementById("content").innerHTML = response;
addBehaviour(); // add the behaviour
},
error: function() {
console.log('failure');
}
});
});
}
addBehaviour();
});
im trying to load a piece of html inside a jquery dialog, this piece of code is located in a separated file, but sometimes fails to load it right. It happens like this :
This is how it should have been displayed.
But sometimes(many times actually) does this:
This is the code that calls the dialog
.click(function(){
var me = this;
$.ajax({
type:"POST",
url:"../CuentaEquipo.php",
dataType: "json",
data:"idEquipo="+$(this).attr("idEquipo")+"&idTorneo="+$(this).attr("idTorneo")+"&action=100",
success:function(data){
if(data.data == 1){
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
cuentas.dialog('open');
}
And this is the code i'm trying to load (AdministracionCuentaEquipo.html)
<script type="text/javascript">
$("#accioncuentas").tabs();
$(".test").button().click(function(){alert("ASDF")});
</script>
<div id="accioncuentas">
<ul>
<li>Abonos</li>
<li>Cargos</li>
<li>Saldos</li>
</ul>
<div id="abonos">
<button class="test">HI</button>
</div>
<div id="cargos">
<button class="test">HI</button>
</div>
<div id="saldos">
<button class="test">HI</button>
</div>
</div>
The only thing that works is closing and opening when this happens, but it's very annoying to do that. It's there any fix or i'm doing something wrong with the ajax or anything else?
Thanks .
I think the problem is that you are creating/opening the dialog before the HTML has properly been parsed.
From the jQuery documentation:
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed.
So try changing this code:
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
to:
var cuentas = $("#cuentas").load("AdministracionCuentaEquipo.html", function(e)
{
$("#cuentas").dialog({
stack:true,
autoOpen:false,
close:function(){
$(this).dialog("close");
}
});
EDIT: the line $("#accioncuentas").tabs(); might also fire too early, so you could change that script tag to wrap it in a function and call that function in your other code.
Example:
<script type="text/javascript">
function InitializeTabs()
{
$("#accioncuentas").tabs();
}
</script>
and then add the line InitializeTabs(); to your code, for example above the line $("#cuentas").dialog({.
SECOND EDIT: I actually think Dasarp is correct in saying that the $("#accioncuentas").tabs(); is the main problem. Either wrap it in a function as I suggested, or move the entire <script> tag down to the bottom of the file (below all your HTML).