JS Trigger submit event while preventing default - javascript

I have a from I added a event listener to for the submit event like this:
form.addEventListener('submit',function(event){
event.preventDefault();
/*some few hundred more lines*/
},false);
My issue is when I use this bit of js later on:
from.dispatchEvent(new Event('submit'));
The function is processed, but the page is reloaded because preventDefault() had no effect, how can a dispatch a event and not trigger the default?

1) you also need e.stopPropogation(), and even though it's redundant these days, to cope with old IE, it's good form to return 0 at the end
2) practically speaking, just stop making the button a submit button. submit explicitly means "send to the other end." just handle the button's onclick instead.

Setting the action on the form to javascript:void(0); instead of # worked.

Related

Allow HTML form validation but stop submit once complete

I know a way to stop a form from submitting, but i have a on click event to the submit button and its firing even though the form doesnt pass the HTML validation.
<form id="signupform" class="signupform" onsubmit="(e)=>{e.preventDefault()};return false">
</form>
My goal is to stop the page refresh either way (if it validates or not) but still allow the built in validation to run first.
Any suggestions?
A submit button's job is to trigger the submit event of a form. Therefore, with form elements, you don't set up click events on the submit button, you set up submit event handlers on the form.
Then, to introduce validation into the mix, you can stop the native submit to take place in the handler, only if validation fails. This is done by accessing the event argument that is automatically sent to every DOM event handler* (see next paragraph for caveat). You can use the event.preventDefault() method to stop the native event from taking place.
*One final note, the use of inline HTML event handling attributes such as onsubmit and onclick is to be avoided. This is a 25+ year old technique that we used before we had standards and unfortunately, because they seem easy to use, they get copied by new developers who don't know any better. There are real reasons not to use them and you've stumbled into one. Your e argument to your event handling function is not being populated with a reference to the event like you think it is. That only happens when you use the modern standard way of setting up event callbacks, which is .addEventListener().
// Set up a submit event handler for the form
// not a click event handler for the button because
// clicking a submit button triggers the form's submit event
document.querySelector("form").addEventListener("submit", function(event){
if(document.querySelector("input").value === ""){
// Invalid data! Stop the submit!
event.preventDefault();
alert("Please fill in all fields!");
return;
}
// If the code reaches this point, validation succeeded
console.log("Form submitted");
});
<form action="https://example.com" method="post">
<input>
<button>Submit</button>
</form>

PrototypeJS Bind Form submit and click

I have a form. I bind the form "submit" event to a method. I also bind the forms container layer to a "click" event method. My on "submit" routine is never reached. If I define the on submit from the console the routine is called. So what is wrong? A couple of things to note: 1) I perform the event binding after dom:loaded. 2) My layers are hidden on start (not sure if that makes a difference)
Here is my binding routines in an anonymous dom:loaded function:
$('edit_billboard').on('click', _console.handleBillboardScreenClick.bind(_console));
$('edit_billboard').down('form').on('submit', _console.handleBillboardSubmit.bind(_console));
Thanks, that is all.
Make sure to stop the forms event propagation. Otherwise your code might not be able to complete before your browser redirects to the action attribute of your form.
_console.handleBillboardSubmit = function(event){
event.stop();
// stuff
}
If you intent to redirect the client, do it manually by seting the location.href after your code hash finished.

Breaking .preventDefault()

Whenever I use preventDefault(), I typically place it at the top of the event handler, like so:
$('#foo').on('click', function(e){
e.preventDefault();
// do stuff
});
Is there any harm in placing it at the bottom of the event handler, and doing stuff before you invoke e.preventDefault()?
Another way of phrasing this question: can you be sure that, by including e.preventDefault() anywhere within the event handler, you will never follow through - say, to the target on a link or the submission of a form?
I've set up a fiddle that you can play with here: http://jsfiddle.net/tuanderful/SMdrN/
Yes.. where you place the statement is irrelevant.
As long as e.preventDefault() is called within the handler the default action will not be triggered
You can place it wherever you want, you can even call e.preventDefault(); inside some if block, it doesn't change the behavior
As long as nothing goes wrong in the code, it doesn't matter where you call preventDefault.
If you put it first in the code, it will prevent the default action even if the script crashes further on.
If you put it last in the code, it will only prevent the default action if the script didn't crash anywhere on the way.

preventDefault() doesn't prevent the action

When I use event.preventDefault() on a link it works, however when I use it on a button doesn't!
DEMO
My code:
<a id="link" href="http://www.google.com">link</a>
<button id="button" onclick="alert('an alert')">button</button>​
$('#link').click(function(event){
event.preventDefault();
});
$('#button').click(function(event){
event.preventDefault();
});
​
Link action is cancelled, but when I click on the button, still executes the onClick action.
Any help? what I want to do is to prevent the button onClick action without changing the button html (I know how to do
$('#button').removeAttr('onclick');
You want event.stopImmediatePropagation(); if there are multiple event handlers on an element and you want to prevent the others to execute. preventDefault() just blocks the default action (such as submitting a form or navigating to another URL) while stopImmediatePropagation() prevents the event from bubbling up the DOM tree and prevents any other event handlers on the same element from being executed.
Here are some useful links explaining the various methods:
http://api.jquery.com/event.preventDefault/
http://api.jquery.com/event.stopPropagation/
http://api.jquery.com/event.stopImmediatePropagation/
However, since it still doesn't work it means that the onclick="" handler executes before the attached event handler. There's nothing you can do since when your code runs the onclick code has already been executed.
The easiest solution is completely removing that handler:
$('#button').removeAttr('onclick');
Even adding an event listener via plain javascript (addEventListener()) with useCapture=true doesn't help - apparently inline events trigger even before the event starts descending the DOM tree.
If you just do not want to remove the handler because you need it, simply convert it to a properly attached event:
var onclickFunc = new Function($('#button').attr('onclick'));
$('#button').click(function(event){
if(confirm('prevent onclick event?')) {
event.stopImmediatePropagation();
}
}).click(onclickFunc).removeAttr('onclick');
you need stopImmediatePropagation not preventDefault. preventDefault prevents default browser behavior, not method bubbling.
http://api.jquery.com/event.stopImmediatePropagation/
http://api.jquery.com/event.preventDefault/
The preventDefault function does not stop event handlers from being triggered, but rather stops the default action taking place. For links, it stops the navigation, for buttons, it stops the form from being submitted, etc.
What you are looking for is stopImmediatePropagation.
you can try this:
$('#button').show(function() {
var clickEvent = new Function($(this).attr('click')); // store it for future use
this.onclick = undefined;
});
DEMO
It have helped me
function goToAccessoriesPage(targert) {
targert.onclick.arguments[0].preventDefault();
...
}

Onclick event override with firebug

I have added an onclick event, which opens a new tab/page, to a button which has an action already (I don't know which action cause it isn't displayed in source, or maybe it's a form submit action).
Button originally also opens a page in new tab, what I want to do is fire up some function after my onclick attribute executes which will stop execution and that default page opening will not happen, only my page will load.
Is there something that can be done?
It sounds like the event is bubbling up after you have handled it. To stop this happening, add event.cancelBubble = true at the end of your handler.
Using jQuery, you can do this:
$('button').click(function() {
//do something
return false; // stop the event from propagating
});
Try getting your function that your call on the onclick event to return false. This will cause any existing action by the button to be overridden
If the handler was set using 'onclick=' you can simply rewrite the onclick property.
If a handler was added to an element with addEventHandler or attachEvent, you can remove it with removeEventHandler or detachEvent, using the same parameters that were used to set it.
If you don't know the setter, or if it used an anonymous function, you can't remove it.
You could replace the element with a duplicate that has no events and set your own on the new element.
(cloneNode is not supposed to clone events, but it sometimes does in some browsers.)

Categories