How to Prevent Bubbling For Form Submit - javascript

I have form that calls the function GenerateWords when it is submitted and returns false.
<form id="3Form" onsubmit="GenerateWords(this); return false;">
This is causing problems with Google Tag Manager implementation as it does not bubble up to the form submit listener.
I understand event.preventDefault(); needs to be used and return false removed but don't know how to implement this. The current javascript I have is:
function GenerateWords(F) {
var strWords = F.words.value;
if ... condition is false
return false;
}
if ... condition is false
return false;
}
vars declared
for (var i = 0; i < ctLines; i++) {
var strLine = arrLines[i];
strLine = Trim(strLine.replace(/[\r]/g,""));
if successful condition
}
}
F.result.value = oResult.join("");
F.result.focus();
}
Any help would be appreciated. Thanks.

Try this in javascript:
function GenerateWords(F,ev) { // event object
...
if(someCondition) // condition when the form should not be submitted.
ev.preventDefault();
}
and you may remove return false; from the form tag and pass the event reference
<form id="3Form" onsubmit="GenerateWords(this,event);">

Related

page gets refreshed on submit click

i have multiple validation on my form.. when i enter wrong data and click on submit button its shows the error message for a second and page gets refreshed..This is only few functions.there are other functions also.. Individually, they work fine. but when i try to run all , it doesnt work.
javascript:
function req()
{
if (document.reg_indi_form.txt_fnm.value=="")
{
document.getElementById('i').innerHTML="*This field is required";
document.getElementById('i').style.color="red";
document.getElementById('i').style.fontSize="12px";
}
if (document.reg_indi_form.txt_lnm.value=="")
{
document.getElementById('i1').innerHTML="*This field is required";
document.getElementById('i1').style.color="red";
document.getElementById('i1').style.fontSize="12px";
}
return false;
}
function validateUname() {
submitFlag = true;
var len=document.reg_indi_form.txt_usrnm.value.length;
if(len<6){
submitFlag=false;
document.getElementById('i2').innerHTML="*enter atleast 6 char";
document.getElementById('i2').style.color="red";
}
return submitFlag;
}
function alls()
{
req();
validateUname();
}
html:
<form name="reg_indi_form" method="post" onSubmit="return alls()" enctype="multipart/form-data">
There is also php code in my file.
Change your function alls() to:
function alls()
{
return req() && validateUname(); // Your function must return false otherwise it will be considered as true
}
Whenever you are binding event & want to stop propagation, just return false ( which you are doing ) but your function alls() was not returning anything which will not stop event propagation further.
Your functions alls() has no return statement and therefore returns an undefined. The only return value that prevents the default action is false. Any other return value, including undefined, allows the default action to take place.
change your function alls() to look like this:
function alls() {
req();
return validateUname();
}
In function alls()
function alls()
{
return req() && validateUname(); // Equivalent to-- if(req() && validateUname()) {return true;} else{ return false;}
}

Checking all forms on site

I need to check some forms (~10) on my site.
I wrote function which will change class of inputs, so they would become red.
function validate()
{
var result = true;
var inputList = document.getElementsByTagName("input");
for (var i=0; i<inputList.length; i++)
if (inputList[i].type == 'text')
{
if(inputList[i].value == "")
{
inputList[i].className='error';
inputList[i].onchange = function()
{
this.className='';
resetEvents(this);
}
result = false;
}
else
{
inputList[i].className='';
}
}
return result;
}
There are no problems with it. I checked it with some forms and it works fine. If I want form to be submitted I should add return validate(); to onSubmit action:
<form class='form' id='form' action='' method='post' onSubmit='return validate()'> Now I need to set onSubmit-actions of all forms.
I want to assign forms handler on page loaded:
window.onload = function() {
var formList = document.getElementsByTagName("form");
for (var i=0; i < formList.length; i++)
formList[i].onsubmit = return validate();
}
This code don't work, because of return validate();, but if I remove return and will just assign handler all inputs would be with .error class already on page load.
What I have to make this working correct?
you need to assign the function reference to the onsubmit handler, not the value returned by validate method
formList[i].onsubmit = validate; //this inside validate will refer to the submitted form
Demo: Fiddle
But I will prefer to use jQuery submit handler(this inside the validate method will refer to the clicked form)
jQuery(function(){
$('form').submit(validate)
})
Demo: Fiddle
Note: it has one drawback, that is since you are returning false from validate it will prevent both the default action and the propagation of the submit event.

Stop redirect in JavaScript

I have a function which verifies if some fields have been filled out (if length > 0) before submitting. If it fails to submit, I don't want to redirect the client at all. Right now, I have the following:
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
document.getElementById('my_form').submit();
return void(0);
}
else
{
document.getElementById('my_form').action = null;
}
}
However, it doesn't matter if verify() returns true or not, I still redirect the client and wipe her inputted fields. How do I keep the client on the page if a required field is blank? (I don't want to lose her currently filled out form...)
Also, I can't use the slick JQuery libraries, since it's not supported on some older browsers. (I'm trying to capture the most general audience.)
This is how I would try to solve this:
document.getElementById('my_form').onsubmit = function( e ){
var event = e || window.event;
// function payload goes here.
event.returnValue = false;
if ( event.preventDefault ){ event.preventDefault(); }
return false;
}
Can be used with event delegation too.
return false to the form!
<form onsubmit="return onSubmit()">
function onSubmit()
{
if (verify()) //This function will throw alert statements automatically
{
return true;
}
else
{
return false;
}
}
to stop the form from submitting, return false from your onSubmit

Respect regular onsubmit handlers from jQuery.submit

I want a jQuery form submit handler to respect any previous submit handlers, including ones added with onsubmit.
I'm trying to detect the previous handler's return value but can't seem to do it:
<form><input type="submit" /></form>
<script type="text/javascript">
$('form')[0].onsubmit = function() { return false; }; // called first
$('form').submit(function(e) {
console.log(e.result); // undefined
console.log(e.isDefaultPrevented()); // false
console.log(e.isPropagationStopped()); // false
console.log(e.isImmediatePropagationStopped()); // false
});
</script>
Is there a way to do this?
I found one non-jQuery way to do this:
var form = $('form')[0];
var old_onsubmit = form.onsubmit;
form.onsubmit = function() {
if ($.isFunction(old_onsubmit)) {
if (old_onsubmit() === false) {
console.log("false");
return false;
}
}
console.log("true");
return true;
}
But I'd much prefer detecting this from the jQuery-bound submit handler

What is the event to catch form submission in Javascript?

A couple of questions here:
I was wondering what event do I use to execute some Javascript on form submission (to do some validation)?
Once I have done my validation, how do I then submit the form in Javascript ?
Let's say you have a form named myForm:
var form = document.getElementById('myForm');
To catch submission:
try {
form.addEventListener("submit", someFunction, false);
} catch(e) {
form.attachEvent("onsubmit", someFunction); //Internet Explorer 8-
}
Note: If you want to stop the form from submitting, you make someFunction return false.
To submit the form:
form.submit();
You can use addEventListener(event, callback) but it's never been properly supported by Internet Explorer.
IE uses attachEvent(event, callback) instead.
I strongly recommend using a prebuilt addEvent function (lots available out there) or a library like jQuery, Prototype, Mootools, etc. since they all have excellent event handling functions built-in.
If you use jquery, it has a nice built-in form submission event hook that can make life very easy. Check out the following:
http://docs.jquery.com/Events/submit
1) Are you looking for OnSubmit event?
2) You can call a function like validate() on onsubmit event and return false if validation fails. If false returned return false from the onsubmit function.
may be like,
<form name="test" OnSubmit = "return Submit()">
function Submit()
{
return Validate()
}
function Validate()
{
//Validation code goes here
}
I took a look at the comments by Serhiy on Sasha's post. The JsFiddle example Serhiy provided was interesting, and I wanted to write an answer that describes the behavior that Serhiy mentioned:
Let's say you have a form named myForm:
var form = document.getElementById('myForm');
To catch submission when using a submit button (<input type='submit' >):
try {
form.addEventListener("submit", validationFunction, false);
} catch(e) {
form.attachEvent("onsubmit", validationFunction); //Internet Explorer 8-
}
Note: If you want to stop the form from submitting, you make validationFunction return false.
To submit the form via javascript:
form.submit();
NOTE: If you use an <input type="button" onclick="form.submit()" />, the onsubmit event handlers added with the attachEvent will not be called. Therefore, you should use something like:
<input type="button" onclick="if (validationfunction()) form.submit();" />
or alternatively if you have a button:
You can add javascript to attach to the button's click event.
var btnValidateAndSubmit = document.getElementById("btnValidateAndSubmit");
try {
btnValidateAndSubmit .addEventListener("click", validationAndSubmitFunction, false);
} catch(e) {
btnValidateAndSubmit .attachEvent("onclick", validationAndSubmitFunction); //Internet Explorer 8-
}
Finally, let's say you are working off a SharePoint web form for editing a list item, and you want to add custom validation to the web form. You can add the following javascript to the web form to add custom validation to the onclick for the OK buttons.
var oElements = document.getElementsByTagName("input");
for (var i=0; i< oElements.length; i++)
{
var elementName = oElements[i].getAttribute("Title");
var elementType = oElements[i].getAttribute("type");
var elementValue = oElements[i].value;
if (elementType=="button" && elementValue=="OK")
{
var okbutton = oElements[i];
// alert("typeof okbutton.onclick = "+typeof okbutton.onclick);
if (typeof okbutton.onclick == "function")
{
var previousfunction = okbutton.onclick;
okbutton.onclick = function()
{
if (validateForm())
{
previousfunction();
}
};
}
else
{
var aspnetForm = document.getElementById("aspnetForm");
aspnetForm.attachEvent("onsubmit",validateForm);
okbutton.onclick = function()
{
if (validateForm())
{
aspnetForm.submit();
}
};
}
}
}

Categories

Resources