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.
Related
I am newbie in Webflow, In Webflow project I want to get button by id and execute some Javascript code when I click this button.
The code I write:
<script>
document.addEventListener('DOMContentLoaded', () => {
let btn = document.getElementById('myButtonId');
btn.addEventListener('click', () => {
// handle the click event
console.log('clicked');
alert("Hello");
});
});
</script>
You'll either need to move the code to the Page Footer,
or wrap the code in the Webflow's recommended "Webflow ready function":
var Webflow = Webflow || {};
Webflow.push(function() {
// Your code goes here
document.addEventListener('DOMContentLoaded', () => {
let btn = document.getElementById('myButtonId');
btn.addEventListener('click', () => {
...
});
});
}); // End Webflow ready function
Java script you can call the function any name you want
<script>
function yourFunctionName() {
alert("hello")
};
</script>
HTML
<body>
<button id="myButtonId" onclick="yourFunctionName ()">click here</button>
</body>
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>
I really thought at first that my code is not working.. but then i tried to create a very simple click event in a clean page and my jquery works on .html but when i open the .php on my XAMPP server it does nothing when it's clicked but it alerts the first one.
index.php
<html>
<head>
<script src="js/jquery-3.2.0.min.js"></script>
</head>
<body>
<?php include "includes/widgets/login.php"; ?>
</body>
</html>
login.php
<script type="text/javascript">
$(document).ready(function() {
alert("Something");
t = clicked();
$('#login').click(function() {
alert("Login Alert!");
});
function clicked() {
alert("I was clicked!");
}
});
</script>
<input type="button" value="Login" id="login" onclick="clicked()">
place the function clicked(); outside from the document.ready();
Change login code to following and it will work.
<script type="text/javascript">
$(document).ready(function() {
alert("Something");
t = clicked();
$('#login').click(function() {
alert("Login Alert!");
});
});
function clicked() {
alert("I was clicked!");
}
</script>
<input type="button" value="Login" id="login" onclick="clicked()">
Uncaught ReferenceError: clicked is not defined at HTMLInputElement.onclick (index.php:22)
This problem will also solved. I don't know properly but i thought that browser can't find function inside jquery.
JQuery create function when DOM is ready.But Control onclick property was read by browser while creating a page but they can't find the function becuse it was not ready yet
So I think procedure may be like :
1) Browser read the page and find the function.
2) JQuery ready event will fire.
Place your function like this:
<script type="text/javascript">
$(document).ready(function() {
alert("Something");
t = clicked();
$('#login').click(function() {
alert("Login Alert!");
});
});
function clicked() {
alert("I was clicked!");
}
</script>
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 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>