jQuery multiple events and multiple selectors - javascript

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.

Related

How to avoid multiple loading of jQuery functions?

I am using following code on my page which I am loading in ajax.
$(document).ready(function() {
$('#button_id').click(function() {
//Do Something
});
});
Now When I click on the button action happens multiple times. I know that its happening because I am loading the ajax page multiple times.
Please help me solve this.
You can use .off() to remove existing listeners:
$(function() {
$('#button_id').off('click').click(function() {
//Do Something
});
});
If I am wrong about your implementation I apologize. Your problem may exist because the binding is created on first page load and then on subsequent ajax loads with new scripts being inserted and creating duplicate bindings. You should prevent any bindings from being generated on ajax loads to prevent duplicate bindings unless you are good with cleanup.
If the button you are clicking on exists in the ajax loaded area then you should use delegation to ensure that the click handlers still work.
For example:
$( "body" ).on( "click", "#button_id", function() {
//do something
});
This will add a binding to the body element, but more specifically to the id #button_id. A click event on the button will propagate and bubble up to the body element (or whatever parent element you choose).
This makes it so that dynamic elements can be inserted in the DOM and only one event handler is needed to listen for it.
No need for .on() or .off() calls for individual ajax loads. This allows your bindings to be much cleaner.
Of course, if your button is not likely to exist on the page all the time then it would not be a good idea to keep extra bindings. Only create these types of binding if they are always needed to prevent optimization issues.
A cleaner solution would be to remove that code from the ajax loaded HTML and use one single event handler in the master page
I guess your problem is the event is firing many times.
To fire only once try this:
$(document).ready(function() {
$('#button_id').on("click",function(e) {
e.preventDefault(); // This prevents the default non-js action (very used for anchors without links or hashes)
e.stopPropagation(); // Prevent the bubling of the event and spread more times
//Do Something
});
});
If doesn't work with e.stopPropagation(); try with e.stopInmediatePropagation();
Adding documentation for the last method I suggested. It could solve your problem.
http://api.jquery.com/event.stopimmediatepropagation/

Event managment: Replace click event

I have a button with a click event (from a 3. party library) which submits a form. I like to remove the click event, add my own function and call the original event after a validation.
I thought i just add an event.stopImmediatePropagation(); but that did not work. Maybe because of the order the events where added(?).
Is the another way to manage the event execution?
Or how can I get the old event to do something like this:
originalClickEvent = $('#button').doSomeMagicAndGetTheEvent('click');
$('#button').unbind();
$('#button').bind('click', function (event) {
if (valid()) originalClickEvent();
});
Look here Remove all JavaScript event listeners of an element and its children?
After you remove the event listeners you can attach your custom event.
If I've understood you correctly this is the effect you're searching for: http://jsfiddle.net/ftGHq/
In case the click event is just bound to one function you could overwrite that function:
var oldFunction = theOldFunction;
function myFunction(control) {
oldFunction(control);
}
$('#button').unbind();
$('#button').click(myFunction);

How do I prevent a programmatic form submit from JS?

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

Jquery remove and add back click event

Is it possible to remove than add back click event to specific element? i.e
I have a $("#elem").click(function{//some behaviour});, $(".elem").click(function{//some behaviour});(there are more than 1 element) while my other function getJson is executing I'd like to remove the click event from the #elem, and add it again onsuccess from getJson function, but preserve both mouseenter and mouseleave events the whole time?
Or maybe create overlay to prevent clicking like in modal windows? is that better idea?
edit :
I've seen some really good answers, but there is one detail that I omitted not on purpose. There are more than one element, and I call the click function on the className not on elementId as I stated in the original question
Rather than using unbind(), which means you'll have to rebind the same event handler later, you can use jQuery's data() facility with the ajaxStart and ajaxStop events to have your elements ignore click events during all AJAX requests:
$(".elem").click(function() {
if (!$(this).data("ajaxRequestPending")) {
// some behaviour
}
}).ajaxStart(function() {
$(this).data("ajaxRequestPending", true);
}).ajaxStop(function() {
$(this).removeData("ajaxRequestPending");
});
EDIT: This answer is also id-to-class-proof (see questioner's edit), since everything matching the selector will handle the AJAX events the right way. That's the main selling point of jQuery, and it shows.
You are looking for .unbind(). Pass it 'click' and it will destroy the click event.
I would put it just before your getJSON and re-bind the click event inside the success handler of your ajax call.
You have to do some additional scripting. There is no callback for that. Take a look over here: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?
Rather than unbinding/binding the click event, you could check the state of another variable to see if it should do the action.
var MyObject = {
requestActive = false;
};
function MyJsonFunction() {
// when requesting
MyObject.requestActive = true;
//...
// when request over
MyObject.requestActive = false;
}
$("#elem").click(function{
if (MyObject.requestActive == true) {
//do something
}
});

jQuery override form submit not working when submit called by javascript on a element

I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with e.preventDefault() and runs an AJAX command. This works fine when the submit button is clicked but when a link with onclick='document.formName.submit();' is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?
A couple of suggestions:
Overwrite the submit function to do your evil bidding
var oldSubmit = form.submit;
form.submit = function() {
$(form).trigger("submit");
oldSubmit.call(form, arguments);
}
Why not bind to all the <a> tags? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag):
$("form a").click(function() {
$(this).parents().filter("form").trigger("submit");
});
If you are using jQuery, you should be attaching events via it's own event mechanism and not by using "on" properties (onclick etc.). It also has its own event triggering method, aptly named 'trigger', which you should use to activate the form submission event.
Thanks Eran
I am using this event binding code
this._form.bind('submit', Delegate.create(this, function(e) {
e.preventDefault();
this._searchFadeOut();
this.__onFormSubmit.invoke(this, new ZD.Core.GenericEventArgs(this._dateField.attr('value')));
});
but there is legacy onclick code on the HTML and I would prefer not to change it as there are just so many links.
This worked for me:
Make a dummy button, hide the real submit with the name submit,
and then:
$("#mySubmit").click(function(){
$("#submit").trigger("click"); });
set an event handler on your dummy to trigger click on the form submit button. let the browser figure out how to submit the form... This way you don't need to preventDefault on the form submit which is where the trouble starts.
This seemed to work around the problem.

Categories