How do I prevent a programmatic form submit from JS? - javascript

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

Related

How to trigger the blur event on CKEditor textareas?

We have some code for validating input on a CKEditor textarea that runs on blur. We add a class of ckeditor_textarea to all textareas that use CKEditor and run this code to attach the necessary functions to the blur event:
$("textarea.ckeditor_textarea").each(function(){
var textarea_id = $(this).attr("id");
CKEDITOR.instances[textarea_id].on('blur',function(){
// Validation functions here
});
});
This works to fire the validation functions when the blur event happens. But we also need to manually trigger the blur event when the submit button is pressed to run the validation functions on these CKEditor textareas before submitting.
How do you trigger the blur event on a CKEditor textarea? Using jQuery syntax (which of course doesn't work because the CKEditor instance isn't a jQuery object), I'm basically looking for something like this:
$("textarea.ckeditor_textarea").each(function(){
var textarea_id = $(this).attr("id");
CKEDITOR.instances[textarea_id].trigger('blur');
});
You should not mix jQuery events and CKEDITOR events. If you would like to have blur for CKEDITOR instance, register it:
ckeInst.on('blur', function(e){
});
And then, if you really want to trigger blur event, you do it like this:
ckeInst.focusManager.blur( true );
Editor is retrived from event (if you have it), or via CKEDITOR.instances['yourCkeName'];
For submit validation I would suggest using the updateElement() method within your submit handler, then run your validation code:
Following will update any and all elements using editor on a page:
$('form').on('submit', function(e){
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
// run validation code
});
This also makes sure that the form data is up to date with the editors themselves
The only way which reliably and properly worked for me is:
editor.window.$.frameElement.blur();
Based on #charlietfl's answer, I was able to come up with a solution for my situation.
First, I created a function to call that runs the validation code:
function ckeditor_blur_event(textarea_id){
// validation code
}
Then, I changed the first block of code in my question to use the new function:
$("textarea.ckeditor_textarea").each(function(){
var textarea_id = $(this).attr("id");
ckeditor_blur_event(textarea_id)
});
Finally, I trigger the same validation code when the form is submitted:
$("textarea.ckeditor_textarea").each(function(){
var textarea_id = $(this).attr("id");
CKEDITOR.instances[textarea_id].updateElement();
ckeditor_blur_event(textarea_id)
});

jQuery multiple events and multiple selectors

Is it possible to use multiple selectors and multiple events in jQuery?
I want to combine the following:
$('#submit-modal').click(function() {
$('#modal-form').submit(function() {
Into something like (or similar):
$('#submit-modal, #modal-form').on('click', 'submit', function() {
I've tried this, but it is not working.
Update (more of what I'm looking to accomplish):
$('#submit-modal').click().$('#modal-form').submit(function() {
I only want the click() attached to the #submit-modal and submit() attached to the #modal-form but if either is initiated it runs the same function.
The solution here is to trigger the form submission from the click event so that the code related to form submission is present only in one palce.
$('#submit-modal').click(function() {
$('#modal-form').submit();// $('#modal-form')[0].submit();
});
$('#modal-form').submit(function() {
//do the submit code here
});
You can do this:
$("#submit-modal, #modal-form").on("click submit", function() {..});
This made that the anonimous function executes when you click or submit in #submit-modal or #modal-form
Yah, you might better off keeping each event with each selector, unless they trigger by the same event.

Intercept form onSubmit

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>

Intercept javascript event

Here's what I'm trying to do :
I have a page with some links. Most links have a function attached to them on the onclick event.
Now, I want to set a css class to some links and then whenever one of the links is clicked I want to execute a certain function - after it returns , I want the link to execute the onclick functions that were attached to it.
Is there a way to do what I want ? I'm using jQuery if it makes a difference.
Here's an attempt at an example :
$("#link").click(function1);
$("#link").click(function2);
$("#link").click(function(){
firstFunctionToBeCalled(function (){
// ok, now execute function1 and function2
});
}); // somehow this needs to be the first one that is called
function firstFunctionToBeCalled(callback){
// here some user input is expected so function1 and function2 must not get called
callback();
}
All this is because I'm asked to put some confirmation boxes (using boxy) for a lot of buttons and I really don't want to be going through every button.
If I understand you correctly, is this wat you wanted to do..
var originalEvent = page.onclick; //your actual onclick method
page.onclick = handleinLocal; //overrides this with your locaMethod
function handleinLocal()
{ ...your code...
originalEvent ();
// invoke original handler
}
I would use jQuery's unbind to remove any existing events, then bind a function that will orchestrate the events I want in the order I want them.
Both bind and unbind are in the jQuery docs on jquery.com and work like this...
$(".myClass").unbind("click"); // removes all clicks - you can also pass a specific function to unbind
$(".myClass").click(function() {
myFunctionA();
myFunctionB($(this).html()); // example of obtaining something related to the referrer
});
An ugly hack will be to use the mousedown or mouseup events. These will be called before the click event.
If you can add your event handler before the rest of handlers, you could try to use jQuery's stopImmediatePropagation

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