Override jquery onclick event? - javascript

I have a button in ASP.NET, that renders to HTML as such:
<input id="btn" type="submit" value="clickme">
If I then add the jquery:
$('#btn').click(function(){return false;});
Every time the button is clicked, nothing will happen (i.e. no postback).
This is fine.
Is there any way in Javascript I can programatically invoke the click (which will cause a postback) whilst also disregarding the jquery-attached, return false function?

You can have the event handler accept additional arguments. When triggering the handler with .trigger you can specify values for these arguments, which will let the handler modify its behavior accordingly.
For example:
$("#btn").click(function(event, submitForm) {
submitForm = submitForm || false;
if (!submitForm) return false;
});
// This will not submit the form
$("#btn").trigger("click");
// But this will
$("#btn").trigger("click", true);

The button itself does nothing by default except submitting the form, so try this:
$('#btn').closest('form').submit();

Related

Add another event at runtime

I have this code:
and I would like to add at runtime by JS something like this:
My idea was doing like this but I dont know how to add AND operator:
form.addEventListener('submitForm', function (e) {
e.preventDefault();
alert('onclick handler called');
}, false);
To not change the HTML itself you can do this
window.addEventListener("load",function() {
let saveBut = document.querySelector('a[title="Save"]');
let form = document.querySelector("[name=thisForm]");
form.addEventListener("submit",function(e) { e.preventDefault(); }); // stop submission by other means than the link
saveBut.onclick=null; // remove the inline event handler
saveBut.addEventListener("click",function(e) {
e.preventDefault(); // stop the link's click
if (validate(e, form)) submitForm(form); // call submitForm if valid
});
});
'submitForm' is referenced as a function in your onclick attribute, but you're trying to use it as an event. It won't work like that, <form> doesn't emit an event called 'submitForm', and it's not being called when you call a submitForm function. <form> does have a submit event.
You should avoid using the onclick attribute (and other on* attributes). Use IDs and addEventHandler to add a click event handler. Then you can just write an entire multi-line function in that handler.
You can also use an <input> or <button> of type=submit and then add an event listener of type submit to the form (if your form is a <form> element). Then you will not need to call any other functions from event listeners. The form will handle that.

Stopping form onSubmit without 'return false;'

I'm looking for a cross browser compatible way to stop a form submission without returning false.
For example:
<form action="..." onsubmit="someFunc(this);">
...
</form>
<script type="text/javascript">
function someFunc(form){
// do stuff to stop form submission without return false
}
</script>
I've not found a good way to do this, anybody know if its possible?
Edit:
I've tried both form.preventDefault() and window.event.preventDefault() in someFunc(). It seems like neither prevent the form from submitting in firefox (on a mac).
Solution
It seems like window.event is not available in FF, while it is in Chrome and IE.. thus my previous attempts not working. I solved this by having the first parameter of the function being called in the form's onsubmit to be the event itself. That can then be cancelled.
New form onsubmit looks like so: onsubmit="someFunc(event, this);"
You can use the event.preventDefault() function to stop of form from submitting. Here's an of a form being caught before being submitted in Javascript (with some JQuery):
$("form").submit(function(event) { // You can change "form" to whatever ID/class your form has
event.preventDefault();
}
Done it! I've tested it in Firefox and this definitely works
Here's a link to the JSFiddle: http://jsfiddle.net/bZx3e/. Here's the HTML:
<form id="form"><input type="checkbox" id="checkbox"/><label for="checkbox">Checkbox</label>
<input type="button" onclick="check();" value="Submit"/></form>
And here's the Javascript:
function check(){
if(document.getElementById("checkbox").checked){
document.getElementById("form").submit();}
else{}
}
So, basically, if the checkbox isn't checked, do nothing and if it is, submit the form. This way you could have all your validation before submitting the form.
Each event has an Event object associated with it. In the W3C event model, calling event.preventDefaut will prevent the default action from occuring. However, the only way in the W3C model to get a reference to the related event object is to pass it to the function from the associated listener. For an in–line listener:
<form onsubmit="someFunc(event)" ...>
If you attach the listener using addEventListener, then the related event object will be passed to the listener function as the first argument:
someElement.addEventListener('click', foo, false);
function foo(eventObject) {
var target = eventObject.target; // element on which the click occured
var currentTarget = eventObject.currentTarget; // Element that called the listener
}
However, the listener in the OP is attached in–line and does not pass a reference to the event, so it can't be captured in browsers that only support the W3C model.
It the IE event model, the related event object is available as a property of the window object, so within the function you can do:
var event = window.event;
But the IE model doesn't support preventDefault, however does provide a returnValue property that, if set to false, cancels the default action.
So the most cross–browser way without using return false would be:
<form onsubmit="someFunc(event);" ...>
function someFunc(event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
However, it is very much simpler to use return false as it has been reliably supported by every browser since about NN/IE 2.

preventdefault not preventing when its inside button

I could not make preventdefault to prevent action. I apologize if the answer is too easy but I simply cant find the error. why is it not preventing from entering the link? jsfiddle given below.
http://jsfiddle.net/zwY5p/34/
$('#theForm').click(function(e) {
event.preventDefault();
alert('FORM!');
});
e != event
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
The parameter passed to the handler function is what you need to execute preventDefault on. In your code, you are passing e but calling preventDefault on event.
preventDefault prevents the default browser action. It does not cancel the inline JavaScript, since that runs first. If you have to override that, just remove it (no event listener necessary):
$('#theForm').removeAttr('onclick').
your event parameter name e and the variable you are using event are different,
$('#theForm').click(function(event) {
event.preventDefault();
alert('FORM!');
});
Other than the errors pointed out on other answers there's another small issue, specifically in your markup declaration:
<!-- Use either the closing tag or the slash (/) in the opening tag -->
<button id="theForm" onclick="location.href='http://www.example.com'" />
go to google
</button>
On the topic, you have two different handlers attached to the button element, they are both handling the click event but they are still different and separate things. jQuery won't know about the handler defined in the markup:
var btn = document.getElementById('theForm');
jQuery._data( btn, "events" );
will return an array with a single element which is the handler added via jQuery.
Now you have to re-evaluate the need of two different handlers for the same element and event and apply conditions. Do you really need to do it this way?
You're using 2 'click' events.
You end up using preventDefault once, and it's used after the 1st click event has ran.
If you make your button an href, then your preventDefault will be working.
It will also make more sense, as the JS will be separated from the HTML markup.
Also, of course you must use the same parameter name. (function(event), with event.preventDefault for example).
If you are passing "e" as an event to the function then you should prevent the default action only for that "e" that you have passed and not for "event".
$('#theForm').click(function(e) {
e.preventDefault();
alert('FORM!');
});
jQuery preventDefault() method: http://api.jquery.com/event.preventDefault/

jQuery form Submit doesn't work when there is a callback function

I have searched quite a bit for this but I can't seem to find a solution. The issue I have is that using the jQuery Submit function on a button does not work when there is a callback function defined. For example this is a small test code that I have:
JavaScript
function doSomething() {
alert("Called the function");
jQuery("#form").bind("submit", function() {
alert("Form was submitted.");
});
}
HTML
<form id="form" action="">
<input type="button" onclick="javascript: doSomething();" value="From Button">
<input type="submit" onclick="javascript: doSomething();" value="From Submit">
</form>
Now when I click the button the second alert is not displayed. If I click the submit I get both the alert messages. What I have found is that if I remove the callback function, then the form submit works fine with both the buttons. I have also tried to add an onSubmit on the form but that did not work either.
The version of jQuery I am allowed to use (and not allowed to change) is jQuery 1.3.2. I know it is a very old version but because of corporate reasons I am not allowed to change it.
It should be
jQuery("#form").bind("submit", function() {
alert("Form was submitted.");
});
function doSomething() {
alert("Called the function");
}
You need to bind the submit handler before the submit happens. In your case the form submit happens, then you are registering the handler.
Well, there are multiple things to say here.
First of all, you bound the "submit" handler to the form -- this is correct because forms have a "submit" event, not buttons.
Second all, HTML tags don't submit forms unless their type is "submit". So that explains why the handler you bound to the form's submit handler doesn't run.
Third, every time you execute .bind( ) it will bind another "copy" of the handler to the event, so when you finally click the tag, it will execute multiple times.
And fourth, you don't have to write "javascript:" in your onclick="" attribute. In fact, it's much better practice to leave active javascript code out of your HTML, and instead bind the events -- much like you are doing above -- in a function passed to jQuery. See http://api.jquery.com/ready/
Finally, since you are doing alert right before the submit, I'm guessing you might want to cancel the form submit -- so look into http://api.jquery.com/event.preventDefault/
Here is javascript code that does what you might actually want:
jQuery(function ($) {
$('#form').submit(function (e) {
// do what you have to do
e.preventDefault();
});
});
You are getting confused, you only need one or the other, since you called doSomething by adding the onclick attribute to input element. The jQuery within this function is never called unless you place it outside the 'doSomething' function.
Whats happening is that you are binding a new "submit" callback every time the user clicks the submit button. You don't need the doSomething function at all. Try this:
var $submit = $("#submitButton").bind("submit", function(){
console.log("submit");
});
...
<form>
<input type="text" />
<input type="button" />
<input id="submitButton" type="submit" />
</form>

Can I determine what button was clicked to fire an onSubmit event?

I've got an onsubmit handler added to a form like so:
$('#content_form').bind('submit',function(e) {
source = $(e.target).attr('name');
alert(source);
return false;
});
so e.target = the form element. I'm using several submit buttons, and need to determine which one was actually clicked (in modern browsers, that clicked button is the only one that submits, I'm doing this for IE6 compat - it submits the values of all the buttons).
My only thought it to kill any onsubmit events, and then tie click events to the buttons themselves. This would kill the form functionality entirely if javascript wasn't enabled, so I'd like to avoid this.
An easy (but possibly naive) implementation would be to have the onclick handler for each button set a field indicating which one was the last one clicked. In your submit handler, you could then check the value of this field.
$('#content_form input:submit').bind('click', function(e) {
$('#content_form').submit();
// you can now reference this or $(this),
// which should contain a reference to your button
});
Have you checked out the jQuery Form Plugin? It handles submitting forms via ajax very nicely and will handle this problem (along with many others) for you.
Something else you could do is use preventDefault(); instead of return false

Categories

Resources