Form.onsubmit not working - javascript

I'm creating a script to check something in my code. This script runs successfully on Chrome, but it doesn't run on IE.
This is run on onsubmit in my form
<form id="frm1" name="frm1" method="post" onsubmit="return checkForm();" action="save_dept_add.php">
And this is my script (I've put it in head tag)
<script language="javascript" type="text/javascript">
function checkForm()
{
if (!window.console) {
console = { log: function(){} };
}
var e = document.getElementById("dept");
var xtext = e.options[e.selectedIndex].text;
if(xtext == ""){
console.log("no dept");
alert("Please select your department");
return false;
}else{
console.log(xtext);
var q = document.getElementById("quantity");
var check = q.value;
console.log(check);
if(check == ""){
alert("Please insert a quantity");
return false;
}else{
return true;
}
}
}
Can anyone tell me what is wrong?

Add this to the top of your JavaScript file
if (!window.console) {
console = { log: function(){} };
}

Related

event.preventDefault() not working on mozilla

I'm having problems with a function that works fine in Google Chrome, but sucks in Mozilla:
The JavaScript code is:
<script type="text/javascript">
function gid(id) {
return document.getElementById(id);
}
function validate() {
var x = document.forms["frmSurvey"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if((gid('0_stars').checked==true) || (gid('1_stars').checked==true) || (gid('2_stars').checked==true) || (gid('3_stars').checked==true) || (gid('4_stars').checked==true)) {
if((gid('comment').value != '') && (gid('email').value != '') && (gid('name').value != '')) {
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address. Please write a valid e-mail address!");
return false;
} else {
document.getElementById("frmSurvey").submit();
}
}
else {
alert('You haven`t completed the mandatory fields. Please make sure that you complete the form corectly! Thank you!');
return false;
}
}
else {
alert('You haven`t completed the mandatory fields. Please make sure that you complete the form corectly! Thank you!');
return false;
}
}
</script>
And the form is:
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post" id="frmSurvey" onsubmit="event.preventDefault(); validate();">
...
...
...
</form>
Is there any methods to replace this function with another? I already tried return false; but then it doesn't submit at all!
Add return true to the end of validate.
Then change:
onsubmit="event.preventDefault(); validate();"
... to :
onsubmit="return validate();"
This will cause the form to submit only if it has been validated.
Edit
Once you've done this, you can remove this line from validate():
document.getElementById("frmSurvey").submit();
Try removing the onsubmit in the form element and add this to you js file.
$('#frmSurvey').submit(function( event ) {
event.preventDefault();
});

Issue in submitting - update

Thanks for the input so far.
The logic is there but it still does not want to submit when passing true to submit...
I added an alert to see if it gets called when value is true, but for some strange reason, the 'return false' is not passing value to submit....
I cant understand what the issue is. Starting to get intimidated lol
<form name="newuser" id="form" method="post" action="do_new_user.php" onSubmit="return validateForm(false)">
function validateForm(submitNow){
if (submitNow == true){
alert ('call ok');
return true;
}
else
{
var x=document.forms["newuser"]["name"].value;
var x2=document.forms["newuser"]["surname"].value;
var x3=document.forms["newuser"]["email"].value;
var x4=document.forms["newuser"]["password1"].value;
var x5=document.forms["newuser"]["password2"].value;
if (x==null || x=="")
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Please enter your name.");
return false;
}
if (x2==null || x2=="")
{
$("#form_status p").fadeIn("slow");
$("#form_status").text("Please enter your surname.");
return false;
}
if (x3==null || x3=="")
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Please enter your email address.");
return false;
}
var atpos=x3.indexOf("#");
var dotpos=x3.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x3.length)
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Email address in invalid.");
return false;
}
if (x4==null || x4=="")
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Please enter your password.");
return false;
}
if (x5==null || x5=="")
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Please re-enter your password.");
return false;
}
if (x4!==x5)
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Password Mismatch.");
return false;
}
//Check if username exists.
$.post("http://ryangosden.com/breadcrumbs/check_user_exists.php",
{
x3 : x3
} ,
function(data)
{
var obj = jQuery.parseJSON(data);
if (obj.email_exists == 1)
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Email Address Taken.");
}
if (obj.email_exists == 2)
{
$("#form_status").fadeIn("slow");
$("#form_status").text("Email ok.");
validateForm(true);
}
});
return false;
}
}
If I understand correctly, the form should submit when email is not taken (and all other fields OK)
Which seem to be done at this point of your code :
$("#form_status").fadeIn("slow");
$("#form_status").text("Email ok.");
validateForm(true);
}
You have to catch the argument so you can submit the form, which could be done at the beginning of your function :
function validateForm(submitNow) {
if (submitNow) return true;
[... rest of function...]
}
Thanks to A. Wolff and Karl-André Gagnon for their comments, my first answer was too quick :)
Update:
Here is a working example you can extend on
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
function validateform(submitNow) {
if (submitNow) return true;
else if ($('#input').val()) return validateform(true);
alert('Please enter a value');
return false;
}
</script>
<form id="#form" action="http://google.com" onsubmit="javascript:return validateform()">
<input type="text" id="input"><input type="submit">
</form>

A little help please with a contact form validator script

I have this email form validation script:
<script type="text/javascript" language="javascript">
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
}</script>
Can someone please tell me what do I have to add in this script in order to make the users enter a valid email address. Also I would like in the rest of the fields to make users to enter text (not links).
I've tried to add different pieces of code which I found on different websites but they did not work and this is because I am not sure if I am adding them right.
Thank you for reading my request.
All the best,
Andi
For e-mail checking you can use following code in else part after checking if e-mail is empty
function validateForm(){
var email = document.getElementById("email").value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
and for url with same logic you can use following regular expression
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
following is a working example based on your work, you can improve this code it is only for showing you how it should be.
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
else{
var name = thisform.Name.value;
if (!checkURL(name)) {
alert("name cannot be a url");
return false;
}
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
else{
var email = thisform.Email.value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
else{
if (!checkURL(thisform.Subject.value)) {
alert("subject cannot contain a url");
return false;
}
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
else{
if (!checkURL(thisform.Message.value)) {
alert("message cannot contain a url");
return false;
}
}
}
function checkURL(url){
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
if (url.search(urlRegEx) == -1) {
return true;
}
return false;
}
See this post for regex urls: regular expression for url
See this post for email validation: Validate email address in JavaScript?
See this for X browser event listening, if would use jQuery, ie8 uses attach see this: Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events
I would recommend looping through the form inputs, and checking if its email and if its not run the regex against the link.
(function(){
var validateForm = function(form){
var errors = [], inputs = form.getElementsByTagName('input');
for(var input = 0; input<inputs.length; input++){
var currentInput = inputs[input];
if(currentInput.value === ''){
// handle attributes here for error message, push error message
if(currentInput.attribute('name') === 'email'){
// handle email
// push error message
}
}
}
return errors;
}
var contactForm = document.getElementById('contact');
contactForm.addEventListener('submit', function(e){
var errorMessages = validateForm(contactForm);
if(errorMessages.length === 0){
} else {
e.preventDefault() // stop the form from submitting
// handle your messages
}
}
}());

Disable submit button until form is valid using javascript?

I have a Javascript function like this:
function validatePath()
{
var path = document.getElementById('server_path').value;
if (path.search(":") == -1)
{
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else
{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name)))
{
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
}
}
If the server_path is incorrect it displays the error but the form is still submitted. I don't want user to be able to submit the form until the server_path is correct. How can I do that?
The usual strategy is to use the form's submit handler and return false to stop submission if validation fails:
<form onsubmit="return validatePath();" ...>
Then in the function (pseudocode):
function validatePath() {
if (validation fails) {
return false;
}
// return any value other than false and the form will submit,
// including undefined
}
An other solution:
function validatePath() {
var path = document.getElementById('server_path').value;
var submitButton = document.getElementById('submit');
document.getElementById('path_error').innerHTML='';
submitButton.removeAttribute('disabled');
if (path.search(":") == -1){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
submitButton.setAttribute('disabled', 'disabled');
}
else{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name))){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
submitButton.setAttribute('disabled', 'disabled');
}
}
}
See in action: http://jsfiddle.net/rUcQc/.
You can disable the submit button until the path is correct. Like this
<input type='submit' disabled='true' onclick='return validatePath()' id='submit'/>
I made some changes in your javascript code.
function validatePath() {
var path = document.getElementById('server_path').value;
if (path.search(":") == -1){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else{
var host_name = path.split(":")[0]
var regex = new RegExp("^[a-zA-Z0-9.]*$");
if(!(regex.test(host_name))){
document.getElementById('path_error').innerHTML="Invalid Server Path!";
}
else {
document.getElementById('submit').disabled=false;
}
}
}

Why does my form still submit when my javascript function returns false?

Here is my Javascript formvalidator function:
function companyName() {
var companyName = document.forms["SRinfo"]["companyName"].value;
if (companyName == ""){
return false;
} else {
return true;
}
}
function companyAdd() {
var companyAdd1 = document.forms["SRinfo"]["companyAdd1"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function companyCity() {
var companyCity = document.forms["SRinfo"]["companyCity"].value;
if (companyCity == ""){
return false;
} else {
return true;
}
}
function companyZip() {
var companyZip = document.forms["SRinfo"]["companyZip"].value;
if (companyZip == ""){
return false;
} else {
return true;
}
}
function enteredByName() {
var enteredByName = document.forms["SRinfo"]["enteredByName"].value;
if (enteredByName == ""){
return false;
} else {
return true;
}
}
function dayPhArea() {
var dayPhArea = document.forms["SRinfo"]["dayPhArea"].value;
if (dayPhArea == ""){
return false;
}
}
function dayPhPre() {
var dayPhPre = document.forms["SRinfo"]["dayPhPre"].value;
if (dayPhPre == ""){
return false;
} else {
return true;
}
}
function dayPhSub() {
var dayPhSub = document.forms["SRinfo"]["dayPhSub"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function validateForm() {
if (companyName() && companyAdd() && companyCity() && companyZip() && enteredByName() && dayPhArea() && dayPhPre() && dayPhSub()) {
return true;
} else {
window.alert("Please make sure that all required fields are completed.");
document.getElementByID("companyName").className = "reqInvalid";
companyName.focus();
return false;
}
}
Here are all of my includes, just in case one conflicts with another (I am using jquery for their toggle()):
<script type="text/javascript" src="formvalidator.js"></script>
<script type="text/javascript" src="autoTab.js"></script>
<?php
require_once('mobile_device_detect.php');
include_once('../db/serviceDBconnector.php');
$mobile = mobile_device_detect();
if ($mobile) {
header("Location: ../mobile/service/index.php");
if ($_GET['promo']) {
header("Location: ../mobile/service/index.php?promo=".$_GET['promo']);
}
}
?>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
Here is my form tag with the function returned onSubmit:
<form method="POST" action="index.php" name="SRinfo" onsubmit="return validateForm();">
The validation works perfectly, I tested all fields and I keep getting the appropriate alert, however after the alert the form is submitted into mysql and sent as an email. Here is the code where I submit my POST data.
if($_SERVER['REQUEST_METHOD']=='POST') {
// Here I submit to Mysql database and email form submission using php mail()
It would seem to me that this line is likely blowing up:
companyName.focus();
The only definition I see for companyName is the function. You can't call focus on a function.
This blows up so the return false is never reached.
I would comment out all the code in the validation section and simply return false. If this stops the form from posting then there is an error in the actual code performing the validation. Add each part one at a time until the error is found.
My guess is the same as James suggests that you are calling focus on the function 'companyName'. The line above this seems to be trying to get the element from the document with the same name but you are not assigning this to a variable so that you can call focus on it.

Categories

Resources