I want to stop form from being submitted, and do something else instead (window.location.href redirect to pretty-printed URL). But I cannot even get the basic part of preventing form from submitting.
As far as I understand it something like this should work:
$(function($){
$("#search_form").submit(function(e){
console.log("cancelling submit");
return false;
});
});
I also tried e.preventDefault(), e.stopPropagation(), and various combinations of these. "cancelling submit" gets printed on Firebug console (so the event fires), but the form submits regardless, whatever I do.
jQuery documentation and logic imply that it should work, but it doesn't. Am I doing something wrong?
Hooking to click event might be easier but forms can be submitted in multiple ways - clicking buttons, pressing Enter, and probably something else I haven't thought about, so I'm trying to just take submit event.
I'm testing it all in Firefox.
EDIT: It turned out that <button type='submit' onclick='this.form.submit()'>Search</button> was causing this. It seems silly in retrospect. Thanks to everyone for help.
I've just tested your code at: http://jsfiddle.net/UZwr5/
The code you've provided works in that demo. Most likely you have a error somewhere in your execution that prevents the return false; from running.
try all of them together return false and e.StopPropagation() and e.preventDefault()
but more like this:
if(e.stopPropagation)
{
e.stopPropagation();
}
if(e.preventDefault)
{
e.preventDefault();
}
return false;
This keeps it much more cross browser compliant.
Related
Hi Guys!
The problem is that I have a form which searches etc. The thing that go's wrong is that the first time you use the form nothing happens and it go's to domain/?. I have no idea what the problem is. I've tried a lot of things but nothing seems to be doing the trick. Thanks!
It seems like it doesn't prevent the default action on the first run because I've tried and a console.log inside this function won't run.
$(function () {
$('#search-bar').on('submit', function (e) {
var y = $('#search').val().toLowerCase();
if (y === 'location') {
geoSearch();
} else {
qCall(y);
}
x.val('');
e.preventDefault;
});
});
The forms HTML has not action or method
You probably cut down the form submit with e.preventDefault. According to W3C definition, the preventDefault javascript function do the following :
Definition and Usage The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
For example, this can be useful when:
Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL
So removing e.preventDefault(); from your code should do the trick.
And by the way, you forgot the double '()' behind the function name. I'm pretty sure you made the mistake only on the code posted, but worth the warning, we never know.
As an exercise, I'm trying to add an event listener to an ebay.com element.
Expected result: show an alert and stop the web page from going to the next URL.
What happens: the alert is shown but the next URL is shown anyway.
I found something interesting on the product pages where I'm testing out preventDefault, stopPropagtion and stopImmediatePropagation.
No matter which combinations I use, nothing seem to work.
The basic code is:
$('#binBtn_btn').click(function(evt){
alert('hi');
evt.stopPropagation(); //or any other option.
});
The thing is that I get the alert, but it still goes to the next page, as if I never stopped the propagation.
I read a lot of articles about event handling, but I couldn't find the answer.
Your help is much appreciated.
My best guess it that the Button has its own click handler, and it's firing before yours.
$('#binBtn_btn').data("events") shows us that there is indeed a click event. Remove that using off.
$('#binBtn_btn').off('click');
Clicking the button now will still cause the form the submit, as all we're doing is browsing to a page. The button is actually just an a tag.
$('#binBtn_btn').click(function(e){
alert('Gotcha!');
e.preventDefault();
});
Let's see what happens if we remove their handler, add ours, and then re-add their one...
var existing = $('#binBtn_btn').data('events').click[0];
$('#binBtn_btn').off('click');
$('#binBtn_btn').click(function(e){ alert('foo'); e.stopImmediatePropagation(); return false; });
$('#binBtn_btn').data('events').click.push(existing);
Same, but just looking at the function for the click handler (rather than tweaking the events.click array directly...)
var existing = $('#binBtn_btn').data('events').click[0].handler;
$('#binBtn_btn').off('click');
$('#binBtn_btn').click(function(e){ alert('foo'); e.stopImmediatePropagation(); e.preventDefault(); });
$('#binBtn_btn').click(existing);
As expected, what is now the second handler -- their handler -- doesn't first. (I've added a return false; rather than e.preventDefault();, just to demonstrate different ways of doing things!)
You can check out what they're doing by placing a breakpoint and viewing the existing var above. You'll see that at the end of their function, they do indeed call e.preventDefault();.
Hope this helps.
try using evt.preventDefault() like this:
$('#binBtn_btn').click(function(evt){
evt.preventDefault();
alert('hi');
});
Then it will not go to the next page.
I need this for a chat box. When the user press enter, I want to trigger a callback (to send the message and clean the input field)
So far I got this, but the typing becomes slow:
$('#chat_input').keydown(function(event) {
if(event.keyCode == '13') {
// do something
}
});
How would you optimize this?
UPDATE: It's not a huge slow down, but I can feel it. I'm pretty sure this code is the responsible. I have always had this problem, so I thought it was about time to find a different way if possible.
No, your code are not the guilty one here. Since you are building a chat system, you must be running other scripts as well. But here is another way to look into the problem.
Make a mini form
<form name="chatline" ... >
<input type="text" />
<input type="submit" />
</form>
Then catch the submit event of the form, which will be triggered on enter automatically by the browser
$("form").submit(function() {
//there you go, you caught your enter
});
I would try this:
document.onkeydown = function(event) {
if(event.keyCode == '13') {
// do something
return false;
}
};
This puts the event listener at the top of the DOM graph, giving it the first chance to respond. Returning false also tells the browser that the event is handled. This will prevent it from 'asking' other elements about the event. Also ditching jQuery and managing the event directly will avoid executing more JS than it needs to.
If this is stil slow, I would have to think theres logic elsewhere slowing it down. If this is a chat, adding/rearranging DOM elements in the chat body can cause significant browser overhead. You should try using setInterval to trigger the 'enter' logic every few seconds or so. Try typing (itll randomly send the message), but if you still experience the slowdown, it must be some other logic.
I don't know what is wrong with that, because I was following at every step the tutorial from jquery.com regarding the form submit event.
My Javascript:
[Ofc. latest jQuery library is included].
<script type="text/javascript">
$("form#addFav").submit(function(event) { event.preventDefault(); alert("hello"); });
</script>
Have also tried with the $(document).ready() event:
$(document).ready(function(){
$("form#addFav").submit(function(event) { event.preventDefault(); alert("hello"); });
});
Here is my HTML form code:
<form action="" id="addFav">
<input type="text" name="name" class="thin-d"/>
<input type="submit" value="Send"/>
</form>
So, regarding the above Javascript code, it is supposed to work (I mean it should prevent default action [submitting form] and send the alert then), but it all doesn't work - have tried with thousands of combinations, but I fail'd. So I'm waiting for your solutions. I'd appreciate every one.
You probably have some syntax error or somthing like that somewhere else, because what you have just works.
Are you sure there aren't any JS errors?
P.S. I would alwyas go for the latter code to ensure that the elements are in the DOM before trying to attach events.
For anyone else who has the same problem, and still struggling to solve this issue, try to see if you have illegally reused the id, and try changing the form id to something unique.
I had accidentally given the id to two different DOM elements and the event was being bound to the first element with the respective id and my form was the second one so it was never captured. This had me pulling my hairs for quiet a long.
I just recently ran into the same issue. Jquery on submit would not work on the form, however just changing it to click event worked fine. Still at a loss why .on(submit) or .submit() events will not recognize the form.
$("form#addFav").click(function (event) {
event.preventDefault(); alert("hello");
$(this).submit();
});
this question is old but.. you might have had another submit events firing before yours fired. If these other events contained "return false;" statement then the event execution got interrupted and your code never fired. To put your code BEFORE these events you might use ONSUBMIT form attribute where you can put code that will fire before or at the same time as other events.
I have simple form. I want to use jquery to prevent form submit.
$(document).ready(function() {
$('#searchform').submit(function(e) {
alert('Handler for .submit() called.');
event.preventDefault();
return false;
});
});
This works fine in chrome. It just shows me a alert box and does not redirect. But does not work on Firefox or IE9, it shows the alert and then goes ahead with form submission.
I appreciate any help.
change
event.preventDefault();
into
e.preventDefault();
Since you're already returning false, you don't also need any sort of event.preventDefault() call at all.
The reason that neither of these seem to work for you is that event is undefined, so an exception is thrown when calling event.preventDefault(), so the method handler exits prematurely.
event.preventDefault();
should be
e.preventDefault();
Try that and see if it fixes the problem.