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.
Related
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.
Is there any way we can intercept the html form's onsubmit event?
In my web application, there are several screens containing forms etc. The issue we are facing is when the user presses any button multiple times, the server gets overloaded with same requests.
Some of the forms have event handlers already attached to them(like onSubmit, button.onClick etc).
One way can be to "inject" my button disable code by going through all the screens.
But what I am looking for is a generic solution which can be applied to all the screens by just including the script where the function is written.
I know I can setup callback using jQuery (capturing onSubmit for form), but in the issue in this case is if any screen has a onSubmit registered already, it may not get called.
Any help in this regard appreciated!
I think this piece of code is a good place to start. It should be placed in separate file and included where you want to use it (if you appear to have global list of scripts - its a good place for it)
var suppressed_items = [];
function allowOnlyOne(item,e){
if (jQuery.inArray(item, suppressed_items)==-1){
//hi little item, I haven't saw you before, please go on... but I remember you
suppressed_items.push(item);
return true;
}
else{
//Hey, you have been submitted already, stay where you are!
return false; //or e.preventDefault(), it's a matter of faith :)
}
}
jQuery(document).ready(function(){
//don't worry, it won't replace your `ready` handlers, but just append new handler
jQuery("from").submit(function(e){
return allowOnlyOne(jQuery(this),e);
});
});
You can use the allowOnlyOne function with any item you wish. So, for example to allow single click on all hyperlinks, inside that ready handler add:
jQuery("a").click(e){
return allowOnlyOne(jQuery(this),e);
}
I hope you get the basic idea: catch the event, get the ID of the element that trigger it, fed it to AllowOnlyOne along with event.
Of course you can wrap it all around into self-executing closure to achieve incapsulation and so on...
If you already have jQuery I suggest you use it... All you need to do is make sure is that your form's onsubmit do not have a "return false" or else it can block jQuery's on submit.
Here's what you need to do:
Remove any return false from your form's onsubmit (if any). Don't worry we'll take care of this later in jQuery.
Add a class to your forms... something like "disableOnSubmit". Example:
<form action="something" onsubmit="yourExistingCode" class="disableOnClick">
</form>
OR
<form action="something" onsubmit="yourExistingCode" class="someOtherClass disableOnClick">
</form>
Implement a code similar to:
<script type="text/javascript">
$(document).ready(function(){
$('form.disableOnClick').submit(function(e){
// preventDefault() does the same as "return false;". It
// will not submit the form. If you're not using return false
// and want the form to be submitted remove the line below
e.preventDefault();
// Now diable any submit button
$('input[type=submit], button[type=submit]').attr('disabled, 'disabled');
});
});
</script>
Basically I have an anchor element, <a href='bla..'>link</a>
On click, I first want to do something and only once it's done I want to take the user to the page that it links to. Something like:
$('a').click(function(ev){
ev.preventDefault();
//do something here
ev.refireDefault();
});
Any suggestions?
Update
My apologies! My FireFox decided to cache the previous version of JS, so nothing that I tried worked until a simple CTRL+F5 solved the issue.
Javascript is not multi-threaded. It is event driven and events fire in the order in which you load them. Therefore, if you simply leave out the ev.preventDefault() in your click event altogether, it won't fire the default action until the function exits.
See jsFiddle here
EDIT per #Greg's comment:
The only scenario in which the above is not true is with asynchronous functions. In that scenario you would want to prevent the default action first and then in the asynchronous callback function, re-fire the default action.
preventDefault marks the event as handled so that when your click function exits, the default action isn't taken. If you don't call preventDefault then the default click action won't get called until your click function exits. So remove it and it'll work as you are suggesting.
The link will not go till after the work is done, so you can do:
$('a').click(function(ev){
//do something here
});
after performing your desired action why don't you just redirect it to the page by adding this line:
window.location = 'welcome.php';
It can be done like this:
<a onclick="JavaScriptCodeHere; return true;" href='bla..'>link</a>
1) The onclick needs to be before the href.
2) return true; makes sure that user will be taken to the linked page after your JS code executes. If you use return false; - linked itself will not work, it will just fire your JavaScript on click;
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.
I have an external library that's calling form.submit(). No matter what I do, I can't seem to catch the event when it's called directly like that.
Example: http://jsfiddle.net/cwolves/yXsWc/
Instead of intercepting the event, have you tried intercepting the submit() call itself? You could do something like replace the default submit() function with one of your choosing that only submits if some flag is set. For instance:
var formElem = document.getElementById("myForm");
formElem.oldSubmit = formElem.submit;
formElem.submit = function(myFlag) {
if (myFlag) {
document.getElementById("myForm").oldSubmit();
}
};
This might be a bit hack-ish, but you could unbind the click event from that certain element, then re-bind it to work the way you want it to.
$('button').unbind('click').click(form.onsubmit);
jsFiddle