Multiple onClicks in Submit Button - javascript

I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}

<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}

Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.

Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!

Related

Chrome Alert Box Submits Page Even if Returning False

In my application I have a textbox to search for items. In this textbox I want the user to have to enter at least 2 characters before searching. If there's less than 2 characters then I want to display a simple alert box telling the user to enter at least 2 characters. On my text box code looks like:
function checkSearchLen(obj, defaultEnterButton) {
if (obj.value == 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
alert('Please ENter at Least 2 Characters');
//return false;
obj.select();
obj.focus();
return false;
} else
doEnterKey(defaultEnterButton);
}
function doEnterKey(s) {
if (event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
document.getElementById(s).click();
}
}
<input class="searchtext" id="txtSearch" value="Search" onfocus="this.value = '';this.style.color='black';this.style.fontStyle='normal';" onkeydown="checkSearchLen(this,'MenuBar_imgSearchGo');" name="txtSearch" />
In my javascript the function on every keystroke from the user, it checks the keyCode being pressed looking for the 'Enter' input. If the user presses 'Enter' and the number of characters in the textbox is less than 2 then it should alert the user and return false. But regardless the form is still submitted when the user presses 'Enter'.I also noticed it doesn't hit the 'doEnterKey' function it just submits the form. Any help or suggestions is appreciated.
In Internet Explorer everything works as should, the javascript code stops wait for input from the user then continues, returning false. However in chrome the alert box is displayed it and it still submits the form, almost as if it's not returning the false back to the element.
Pass the event object in the call and on ENTER prevent event default.
I used the keypress event and tested on IE, FF and Chrome.
Now the alert message on form submit will not happen because the ENTER is prevented.
function checkSearchLen(event, obj, defaultEnterButton) {
event = event || window.event;
if (obj.value == 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
alert('Please ENter at Least 2 Characters');
obj.select();
obj.focus();
event.preventDefault();
return false;
} else
doEnterKey(defaultEnterButton);
}
function doEnterKey(s) {
if (event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
document.getElementById(s).click();
}
}
<form action="http://www.google.com" onsubmit="alert('submit');">
<input class="searchtext" id="txtSearch" value="Search" onfocus="this.value = '';this.style.color='black';this.style.fontStyle='normal';" onkeypress="checkSearchLen(event, this,'MenuBar_imgSearchGo');" name="txtSearch" />
</form>
The best method to deal with this kind of problems is by using Jquery...just a few lines of Jquery code is capable of doing what you did in the entire program!
Another alternate answer is to do checking in form submit event and cancel that submit event based on invalid input. This will prevent page post back. Actually, this is the same approach that ASP.Net framework takes when a page has ASP.Net validators in it with client-side validation turned on.
Also, there is no need to cancel the event in doEnterKey, so I have commented two lines in that function.
The following code will work as I have tested on my side. There are two aspects to the logic being used:
A global variable stopSubmit decides if form submit event will be canceled or not. If this variable is true then form submit event will cancel.
The original form submit event code of the form is being pre-pended with our custom JavaScript that will return a false in case the form submit needs to be canceled. This is happening when body loads for the page i.e. body's onload event calls setFormSubmit to modify existing form submit code. If everything was valid, then original form submit code executes without issues and page posts back.
<body onload="setFormSubmit()">
<form id="form1" runat="server">
<asp:Label ID="label1" runat="server"></asp:Label>
<div>
First name:
<input type="text" name="FirstName" value="Mickey" /><br />
Last name:
<input type="text" name="LastName" value="Mouse" /><br />
<input type="submit" value="Submit" />
<input type="text" onkeydown="checkSearchLen(this,'MenuBar_imgSearchGo');" />
<input type="submit" value="Submit" id="MenuBar_imgSearchGo"/>
</div>
<script>
var stopSubmit = false;
function setFormSubmit() {
document.forms[0].setAttribute("onsubmit", " var stopPostback = StopPostback(); if(stopPostback === true) { return false; } " + (document.forms[0].onsubmit === null ? "" : document.forms[0].onsubmit));
}
function checkSearchLen(obj, defaultEnterButton) {
if (obj.value === 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
stopSubmit = true;
alert('Please ENter at Least 2 Characters');
obj.select();
obj.focus();
return false;
} else {
stopSubmit = false;
doEnterKey(defaultEnterButton);
}
}
function doEnterKey(s) {
if (event.keyCode == 13) {
//event.returnValue = false;
//event.cancel = true;
document.getElementById(s).click();
}
}
function StopPostback() {
if (stopSubmit === true) {
stopSubmit = false;
return true;
}
return false;
}
</script>
</form>

I want the user to not be able to advance to the next screen if he/she doesn't enter the required information

The function receives the username and password of the user. If either are left empty, nothing happens and they won't be linked to google.ca if they click the "Go" button. If they filed in the required sections then they will be directed to google.ca. For some reason, if any of the text boxes are left unfilled and the Go button is pressed, it brings me to a 404 error page when I want it to just stay on that page until the user fills the textbox. What is causing this problem? This is the HTML file.
<form action="index.php" method="get" id="form" onsubmit="return go(document.getElementById('username'), document.getElementById('password'))">
<table>
<tr><td>Username: <input type="text" name="username" maxlength="16" id="username" onKeyUp="updateLength('username', 'usernameLength')" onblur="checkTextField(this);"/> <span id="usernameLength"></span></td></tr>
<tr><td>Password: <input type="password" name="password" maxlength="50" id="password" onKeyUp="updateLength('password', 'passwordLength')"> <span id="passwordLength" onblur="checkTextField(this);"></span></td></tr>
<tr><td><input type="submit" value="Go" id="goButton" onclick="go(username, password)"/></td></tr>
</table>
</form>
And here is the js file
function loginFunction() {
var url = "login.html";
window.open(url);
}
function createAccountFunction() {
var url2 = "createAccount.html";
window.open(url2);
}
function go(username, password) {
if (username != null && password != null) {
var url = "https://www.google.ca/";
window.open(url);
}
}
function updateLength(field, output) {
var curr_length = document.getElementById(field).value.length;
var field_mLen = document.getElementById(field).maxLength;
document.getElementById(output).innerHTML = curr_length + '/' + field_mLen;
}
function checkTextField(field) {
if (field.value == '')
alert("Field is empty");
}
You aren't stopping the default event of the onsubmit. You can do that by changing your go function to:
function go(username, password) {
return function(event) {
event.preventDefault();
if (username != null && password != null) {
var url = "https://www.google.ca/";
window.open(url);
}
}
}
You also don't need the return in the HTML. Just call the function.
I didn't understand your code logic, but maybe I can offer you a way to fix your code by yourself.
You have a form and a button. If you click on the button you execute the go() function. Because the button is a submit button, on the same click you execute one more time the go() function.
My advice is to create a new function, you may name it validate():
function validate() {
var username = document.get........
var password = document.get........
// more logic here, if need
if(!username || !password) {
return false;
}
return true
}
and now, your submit button looks like:
<input type="submit" value="Go" id="goButton" onclick="return validate()"/>
The form won't submit if the validate() function returns false.
Hope this helps.

How to Validate form without submitting it

I have a form that I want to validate before the form submits, when I press the Submit button. I know I am supposed to use preventDefault but I am not sure how to use it correctly:
function validateName() {
var name = form.firstname.value;
if (name == "") {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else if (/[0-9]/.test(name)) {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else {
document.getElementById("firstnameInvalid").style.visibility = "hidden";
}
}
<form name="form" method="post" onsubmit="return validate(this)">
<p>First Name:
<input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name" />
<span id="firstnameInvalid" style="color:red; visibility:hidden"> Name is Invalid </span>
</p>
You can stop the form by adding return statement to your validation code. onsubmit will stop the form submit when the function returns false.
your validate() must return a true or false value to it work with onsubmit="return validate(this)"
try something like
function validate(variable)
{
if(condition) //add a condition to validate
{
return false; //if condition are met, return false and do not submit
}
//you can create more than one condition following this logic.
return true; //if none of the conditions are met, he return true and submit
}
As others have said, returning false in your onsubmit callback will prevent the form from being submitted.
var form = document.getElementById( 'idgoeshere' );
form.onsubmit( function() {
// validate here
return false;
});

Javascript function fires twice on clicking 'Submit' button

I'm trying to insert records into DB using AJAX. I'm not sure why, but it seems the javascript function referenced in the onclick tag of the submit button gets fired twice, and hence I get two records in my DB per click.
Placing alerts in the JS, I have managed to figure out that the problem is in the JS function getting called twice, and not the PHP script making two inserts. So, I'm not posting the PHP script, unless asked.
Here's the HTML for the form:
<form id="notify" method="post" action="add_notify.php">
Name: <input type="text" class="formname" name="name" value="" size="20"/>
Email: <input type="text" class="formname" name="email" value="" size="20"/>
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
</form>
Javascript:
$("document").ready(function() {
$("#notify").submit(function() {
processInfo();
return false;
});
});
function processInfo()
{
var errors = false;
// Validate name
var name = $("#notify [name='name']").val();
if (!name) {
errors = true;
document.getElementById('name_error').innerHTML = 'You must enter a name.';
}
var email = $("#notify [name='email']").val();
if (!email)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter an email.';
}
else
{
var validEmail = true;
validEmail = validateEmail(email);
if (!validEmail)
{
errors = true;
document.getElementById('email_error').innerHTML = 'You must enter a valid email address.';
}
}
if (!errors)
{
$("#notify").ajaxSubmit({success:showResult});
return false;
}
}
You are calling processInfo twice once in submit handler and once in click handler. This might be the reason.
Here onclick="processInfo()" and inside
$("#notify").submit(function() {
processInfo();
return false;
});
processInfo() is called twice, both here, when the form submits:
$("#notify").submit(function() {
processInfo();
return false;
});
and here, when you click the submit button:
<input type="submit" class="sendform" name="submit" onclick="processInfo()" value="Go!"/>
You should remove one of them.
You are calling the processInfo() function twice: once on the form submit event, and once on the onclick on the input.
You should only attach the processInfo() function on the submit event. Remove the onlick dom0 event handler (inline scripts are to be avoided).
Also, do not use return false; as it prevents event bubbling. Use ev.preventDefault() instead.
$("document").ready(function() {
$("#notify").submit(function(ev) {
ev.preventDefault();
processInfo();
});
});

JavaScript code returns false, but still the form is submittted

I have a form with JavaScript validation. Upon there being an error, the submit button should 'grey-out' and the form should not be submitted. However, the last couple of functions seem to submit the form even though they pop the alert box. Why?
Button code:
<input type="submit" name="button" id="button"
onclick='return formvalidation();' value="Next" />
Non-working function example:
function BlankSite() {
var SiteNum= document.getElementsByName("sitesinput")[0].value;
if ((SiteNum == "") || (SiteNum == 0))
{
alert("You have not selected an amount of sites.")
document.forms[0].button.disabled = true;
return false;
}
}
Function initiator:
function formvalidation()
{
ZeroPhones();
BlankPC();
BlankSite();
BlankSeats();
phone_change();
} // End of formvalidation
This is very strange and I have tried various workarounds all to no avail!
You need to have return false; in the function called by the onclick, in this case formvalidation.
Having some function called by the "root" function return false has no effect whatsoever. The return value is lost.
They are returning false (and breaking, which is actually unreachable code) but the results are never returned to parent validation function. Your validator, assuming it's bound to the form action, should look like:
function formvalidation(){
{
if (!ZeroPhones())
return false;
if (!BlankPC())
return false;
//
// keep checking for false and return false.
//
// default to return true
return true;
}
So when the functions do in-fact return false, the false return is carried back up through to the bound function.
BlankPC() is called by formvalidation so false is returned into the method formvalidation().
Your formvalidation() is always falling off the end which is the same as returning true.
If you want it to return false when one of your validations fails, it should be:
function formvalidation()
{
retval = true;
retval &= ZeroPhones();
retval &= BlankPC();
retval &= BlankSite();
retval &= BlankSeats();
retval &= phone_change();
return retval;
} // End
This can be optimized a bunch, but you can get the gist of it.
Call the JavaScript function onSubmit of the form instead of calling at button onClick.
JavaScript code
function validate()
{
alert('test');
return false;
}
<form action="test" method="post" onsubmit="return validate();">
This is working fine for me.
formvalidation() isn't returning false.
Maybe you want something like:
function formvalidation()
{
if(!ZeroPhones() ||
!BlankPC() ||
!BlankSite() ||
!BlankSeats() ||
!phone_change())
return false;
}
My solution to this problem was to disable the submit button until the validation was successful. Something along these lines:
function checkPassword() {
// This is my submit button
document.getElementById('nextBtn').setAttribute('disabled', 'disabled');
password1 = document.getElementsByName("pwd1")[0].value;
password2 = document.getElementsByName("pwd2")[0].value;
if (password1 == '') {
// If password not entered
alert ("Please enter Password");
return false;
} else if (password2 == ''){
// If confirmation password not entered
alert ("Please enter confirm password");
return false;
} else if (password1 != password2) {
// If NOT the same, return false.
alert ("\nPassword did not match: Please try again...");
return false;
} else {
document.getElementById('nextBtn').removeAttribute('disabled');
return true;
}
}

Categories

Resources