I am trying to trigger the click event of an a tag using jQuery and have seen many other Stack Overflow posts about this, but can't figure out why my replications of any of them are not working. My HTML is shown here:
<c:url var="link" value="/hardwareItems" />
<a href="${link}" id="goToHardwareItems">Go
to items</a>
And then here is my jQuery/JS:
$("#form").on("submit", function() {
if (confirm("Add hardware items?")){
$("#goToHardwareItems").trigger('click');
}
else {
window.location.href = "/home";
}
});
What I have is not working though, but when I actually click on the link, I am indeed taken to the page. So the problem is that the event is simply not triggering, even though I am also getting into the if statement. What am I doing wrong?
You can read the value of href and redirect. You are already doing so.
$("#form").on("submit", function () {
// Determine where to go based on user's response
var link = confirm('Add hardware items?') ? $('#goToHardwareItems').attr('href') : '/home';
window.location.href = link;
});
I want to focus on specific id (ex. using $('#a')) after submit.
There is nothing special with my code yet.
My javascript code is
function get_info(id){
$(user_id).submit();
$('#a).focus();
};
After submit, it should focus on where id='a'.
But after submit window focus on id='a' and reset the page.
I tried using
function get_info(id){
$(user_id).submit(function(e){
e.preventDefault();
$('#a').focus();
});
};
But this code make program worse. I think it stops performing submit.
Can anyone help me?
As Chris's comment says you couldn't focus on the element simply by using $('#a').focus(); after the submit since the page will be redirected/refreshed.
You need to use cookies or local storage, here a suggested sample using local storage like :
function get_info(id) {
localStorage.setItem('focusItem', '#a');
$(user_id).submit();
};
Then in the ready function, you could add :
$(function(){
var focusItem = localStorage.getItem('focusItem');
if( focusItem != null ){
$(focusItem).focus();
localStorage.removeItem('focusItem');
}
});
function SetFocus(){
$("#FocusingID").focus();}
/***********another way **********************//*
$("#submitbtnId").click(function(){
//your submession and other task;
$("#FocusingID2").focus();
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id=FocusingID>
<button type=submit onclick="SetFocus();">click</button>
To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!
I'm trying to change a href link programmatically (according to a result from an ajax async operation) and open it in a new window (I don't want to use window.open as it behaves like a popup and being blocked in IE).
The following code works only after clicking MANUALLY on the link for a second time, how can I make it work on the first click?
Simplified example:
trying to change href link dynamically
<script type="text/javascript">
document.getElementById('link').addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) //only preventDefault for the first time..
{
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
// --HERE I PERFORM AN AJAX CALL WHICH TAKES A WHILE AND BY ITS RESULT I DECIDE WHICH URL TO USE - BUT HERE I JUST USE IT HARDCODED--
document.getElementById('link').setAttribute("href", "http://google.com");
document.getElementById('link').click();
}
I organized your code in this jsFiddle: http://jsfiddle.net/mswieboda/Hhj4D/
The JavaScript:
var $link = document.getElementById('link');
$link.addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) {
//only preventDefault for the first time..
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
$link.setAttribute("href", "http://google.com");
$link.click();
}
This worked for me when I ran it. Hovering the link, you could see http://demo.com but clicking it takes you to http://google.com. Is this the desired functionality? You can definitely use the updateLink function any time (after an AJAX call) to change the href, also, you could probably set the _target in that function as well, makes more sense to me that way.
Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: "Are you sure you want to navigate away from this page?" blee blah bloo...
Has anyone implemented this before, how do I track that changes were committed?
I believe I could do this myself, I am trying to learn the good practices from you the experts.
I tried the following but still doesn't work:
<html>
<body>
<p>Close the page to trigger the onunload event.</p>
<script type="text/javascript">
var changes = false;
window.onbeforeunload = function() {
if (changes)
{
var message = "Are you sure you want to navigate away from this page?\n\nYou have started writing or editing a post.\n\nPress OK to continue or Cancel to stay on the current page.";
if (confirm(message)) return true;
else return false;
}
}
</script>
<input type='text' onchange='changes=true;'> </input>
</body>
</html>
Can anyone post an example?
Update (2017)
Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been removed from all of them. Browsers now only display generic messages. Since we no longer have to worry about setting the message, it is as simple as:
// Enable navigation prompt
window.onbeforeunload = function() {
return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
Read below for legacy browser support.
Update (2013)
The orginal answer is suitable for IE6-8 and FX1-3.5 (which is what we were targeting back in 2009 when it was written), but is rather out of date now and won't work in most current browsers - I've left it below for reference.
The window.onbeforeunload is not treated consistently by all browsers. It should be a function reference and not a string (as the original answer stated) but that will work in older browsers because the check for most of them appears to be whether anything is assigned to onbeforeunload (including a function that returns null).
You set window.onbeforeunload to a function reference, but in older browsers you have to set the returnValue of the event instead of just returning a string:
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = 'Any text will block the navigation and display a prompt';
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
You can't have that confirmOnPageExit do the check and return null if you want the user to continue without the message. You still need to remove the event to reliably turn it on and off:
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
// Turn it off - remove the function entirely
window.onbeforeunload = null;
Original answer (worked in 2009)
To turn it on:
window.onbeforeunload = "Are you sure you want to leave?";
To turn it off:
window.onbeforeunload = null;
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
To check for values? That depends on your validation framework.
In jQuery this could be something like (very basic example):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
The onbeforeunload Microsoft-ism is the closest thing we have to a standard solution, but be aware that browser support is uneven; e.g. for Opera it only works in version 12 and later (still in beta as of this writing).
Also, for maximum compatibility, you need to do more than simply return a string, as explained on the Mozilla Developer Network.
Example: Define the following two functions for enabling/disabling the navigation prompt (cf. the MDN example):
function enableBeforeUnload() {
window.onbeforeunload = function (e) {
return "Discard changes?";
};
}
function disableBeforeUnload() {
window.onbeforeunload = null;
}
Then define a form like this:
<form method="POST" action="" onsubmit="disableBeforeUnload();">
<textarea name="text"
onchange="enableBeforeUnload();"
onkeyup="enableBeforeUnload();">
</textarea>
<button type="submit">Save</button>
</form>
This way, the user will only be warned about navigating away if he has changed the text area, and will not be prompted when he's actually submitting the form.
To make this work in Chrome and Safari, you would have to do it like this
window.onbeforeunload = function(e) {
return "Sure you want to leave?";
};
Reference: https://developer.mozilla.org/en/DOM/window.onbeforeunload
With JQuery this stuff is pretty easy to do. Since you can bind to sets.
Its NOT enough to do the onbeforeunload, you want to only trigger the navigate away if someone started editing stuff.
jquerys 'beforeunload' worked great for me
$(window).bind('beforeunload', function(){
if( $('input').val() !== '' ){
return "It looks like you have input you haven't submitted."
}
});
This is an easy way to present the message if any data is input into the form, and not to show the message if the form is submitted:
$(function () {
$("input, textarea, select").on("input change", function() {
window.onbeforeunload = window.onbeforeunload || function (e) {
return "You have unsaved changes. Do you want to leave this page and lose your changes?";
};
});
$("form").on("submit", function() {
window.onbeforeunload = null;
});
})
To expand on Keith's already amazing answer:
Custom warning messages
To allow custom warning messages, you can wrap it in a function like this:
function preventNavigation(message) {
var confirmOnPageExit = function (e) {
// If we haven't been passed the event get the window.event
e = e || window.event;
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
window.onbeforeunload = confirmOnPageExit;
}
Then just call that function with your custom message:
preventNavigation("Baby, please don't go!!!");
Enabling navigation again
To re-enable navigation, all you need to do is set window.onbeforeunload to null. Here it is, wrapped in a neat little function that can be called anywhere:
function enableNavigation() {
window.onbeforeunload = null;
}
Using jQuery to bind this to form elements
If using jQuery, this can easily be bound to all of the elements of a form like this:
$("#yourForm :input").change(function() {
preventNavigation("You have not saved the form. Any \
changes will be lost if you leave this page.");
});
Then to allow the form to be submitted:
$("#yourForm").on("submit", function(event) {
enableNavigation();
});
Dynamically-modified forms:
preventNavigation() and enableNavigation() can be bound to any other functions as needed, such as dynamically modifying a form, or clicking on a button that sends an AJAX request. I did this by adding a hidden input element to the form:
<input id="dummy_input" type="hidden" />
Then any time I want to prevent the user from navigating away, I trigger the change on that input to make sure that preventNavigation() gets executed:
function somethingThatModifiesAFormDynamically() {
// Do something that modifies a form
// ...
$("#dummy_input").trigger("change");
// ...
}
The standard states that prompting can be controlled by canceling the beforeunload event or setting the return value to a non-null value. It also states that authors should use Event.preventDefault() instead of returnValue, and the message shown to the user is not customizable.
As of 69.0.3497.92, Chrome has not met the standard. However, there is a bug report filed, and a review is in progress. Chrome requires returnValue to be set by reference to the event object, not the value returned by the handler.
It is the author's responsibility to track whether changes have been made; it can be done with a variable or by ensuring the event is only handled when necessary.
window.addEventListener('beforeunload', function (e) {
// Cancel the event as stated by the standard.
e.preventDefault();
// Chrome requires returnValue to be set.
e.returnValue = '';
});
window.location = 'about:blank';
When the user starts making changes to the form, a boolean flag will be set. If the user then tries to navigate away from the page, you check that flag in the window.onunload event. If the flag is set, you show the message by returning it as a string. Returning the message as a string will popup a confirmation dialog containing your message.
If you are using ajax to commit the changes, you can set the flag to false after the changes have been committed (i.e. in the ajax success event).
Here try this it works 100%
<html>
<body>
<script>
var warning = true;
window.onbeforeunload = function() {
if (warning) {
return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";
}
}
$('form').submit(function() {
window.onbeforeunload = null;
});
</script>
</body>
</html>
You can add an onchange event on the textarea (or any other fields) that set a variable in JS. When the user attempts to close the page (window.onunload) you check the value of that variable and show the alert accordingly.
Based on all the answers on this thread, I wrote the following code and it worked for me.
If you have only some input/textarea tags which requires an onunload event to be checked, you can assign HTML5 data-attributes as data-onunload="true"
for eg.
<input type="text" data-onunload="true" />
<textarea data-onunload="true"></textarea>
and the Javascript (jQuery) can look like this :
$(document).ready(function(){
window.onbeforeunload = function(e) {
var returnFlag = false;
$('textarea, input').each(function(){
if($(this).attr('data-onunload') == 'true' && $(this).val() != '')
returnFlag = true;
});
if(returnFlag)
return "Sure you want to leave?";
};
});
here is my html
<!DOCTYPE HMTL>
<meta charset="UTF-8">
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="myFunction()">
<h1 id="belong">
Welcome To My Home
</h1>
<p>
<a id="replaceME" onclick="myFunction2(event)" href="https://www.ccis.edu">I am a student at Columbia College of Missouri.</a>
</p>
</body>
And so this is how I did something similar in javaScript
var myGlobalNameHolder ="";
function myFunction(){
var myString = prompt("Enter a name", "Name Goes Here");
myGlobalNameHolder = myString;
if (myString != null) {
document.getElementById("replaceME").innerHTML =
"Hello " + myString + ". Welcome to my site";
document.getElementById("belong").innerHTML =
"A place you belong";
}
}
// create a function to pass our event too
function myFunction2(event) {
// variable to make our event short and sweet
var x=window.onbeforeunload;
// logic to make the confirm and alert boxes
if (confirm("Are you sure you want to leave my page?") == true) {
x = alert("Thank you " + myGlobalNameHolder + " for visiting!");
}
}
From the WebAPIs->WindowEventHandler->onbeforeunload, it recommends use window.addEventListener() and the beforeunload event, instead of onbeforeunload.
Syntax example
window.addEventListener("beforeunload", function(event) { ... });
window.onbeforeunload = function(event) { ... };
Note: The HTML specification states that authors should use the Event.preventDefault() method instead of using Event.returnValue to prompt the user.
So, in terms of your case, the code should look like this:
//javascript
window..addEventListener("beforeunload", function(event) {
//your code
// If you prevent default behaviour in Mozilla Firefox prompt will always be shown
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
})
It can be easily done by setting a ChangeFlag to true, on onChange event of TextArea. Use javascript to show confirm dialog box based on the ChangeFlag value. Discard the form and navigate to requested page if confirm returns true, else do-nothing.
What you want to use is the onunload event in JavaScript.
Here is an example: http://www.w3schools.com/jsref/event_onunload.asp
There is an "onunload" parameter for the body tag you can call javascript functions from there. If it returns false it prevents navigating away.