event.preventDefault() not working on mozilla - javascript

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();
});

Related

Form.onsubmit not working

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(){} };
}

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>

java script form validation works fine in chrome but not working in firefox?

form validation using java script works fine on chrome. but not working in firefox.
Code:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["newuserForm"]["mname"].value;
if (x==null || x=="")
{
alert("name must be filled");
return false;
}
var x=document.forms["newuserForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert(" email is not valid");
return false;
}
var x=document.forms["newuserForm"]["password"].value;
if (x==null || x=="")
{
alert("password must be filled out ");
return false;
}
/* var x=document.forms["newuserForm"]["age"].value;
if (x==null || x=="")
{
alert("Age must be Selected");
return false;
}*/
var m = document.getElementById('male');
var f = document.getElementById('female');
if ( (m.checked == false ) && (f.checked == false ) )
{
alert ( "Please select your gender ");
return false;
}
if( document.newuserForm.age.value == "-1" )
{
alert( "please select your age group" );
return false;
}
if( document.newuserForm.country.value == "-1" )
{
alert( "Please select your country");
return false;
}
if( document.newuserForm.city.value == "-1" )
{
alert( "please select your country" );
return false;
}
}
</script>
in chrome if the user doesn't enter name, it will shows a message "name must be filled". but in Firefox nothing shows, if i click the submit button without entering the name it will registering the user. why the java script not working on Firefox? whats wrong with the code?
try this code it is working in firefox also
validation code in javascript for email validation
http://informationiswelth.blogspot.in/

Form shows mistakenly the success alert box when it has invalid input in jQuery

In the script below I check if the email entered is valid. It is not the best regex but it is ok for now. Also for the moment I do not make any server side check for input. Only with this script.
I have this problem though:
When an email is valid, and after I type an invalid email I get first the Your email is not in valid format and then You will be notified when we launch. Thank you! alert. Also the email is sent. How to fix this ?
Thank you
this is my form
<form id="myform" action="" method="POST">
<input id="subscribe" name="subscribe" class="subscribe floatLeft" type="text">
<button id="signUp" class="signUp floatRight" ><intro>notify!</intro></button>
<div class="clear"> </div>
</form>
and here is the script
var signUp = function(inputEmail) {
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(inputEmail)) {
isValid = false;
alert('Your email is not in valid format');
}
$("#myform").submit(function(event) {
event.preventDefault();
if (!isValid) {
return false;
} else {
$.post('mailme.php', $("#myform").serialize(), function(data) {
alert('You will be notified when we launch. Thank you!');
});
return false;
}
});
};
You need the onsubmit event to return false;
You need to bind the submit event anyway and make the isValid check there;
$("#myform").submit(function(event){
event.preventDefault();
if(!isValid){
return false;
}else{
$.post(...)
return false;
}
});
--Edit--
Forgot to return false/event.preventDefault; But like i said, the submit event need to be bound anyway
--Edit2--
function validEmail(email){
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email.test(emailReg)
}
$(document).ready(function(){
$("#myform").bind({
submit: function(e){
e.preventDefault();
if(validEmail($("#myform").find("#subscribe").val()){
$.post(...)
alert("You will be notified");
return false;
}
else {
alert("Invalid email");
return false;
}
});
});
}
You need to return false or event.preventDefault() in the emailReg test.

Form submission will not stop for validation

What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.
<form id="rfq" name="rfq" action="rfq_form" method="post" enctype="multipart/form-data">
...
<input type="image" id="submit" name="submit" src="submit.png" border="0" />
JS email validation:
//$("#rfq").submit(function() { doesnt seem to work either
$('#submit').click(function() {
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return false; // cancel form submission if email invalid
}
return false; // return true if no errors once i get it working
});
Working Example
First, make sure all event handlers are attached once the DOM is "ready"
I'm using .submit() on the actual form.
$(document).ready(function() {
// now that document is "ready"
$('#formId').submit(function() {
var email = $('#emailInput').val();
alert(email);
if(email.indexOf("#") == -1){
alert("invalid!");
return false; // cancel form submission if email invalid
}
alert("valid!");
return true; // return true if no errors once i get it working
});
});
Try wrapping your code in a ready block.
$(document).ready(function(){
// your code here
});
You should also be using the submit event on the <form> element, I think.
This is going to work. If you don't understand why, feel free to ask :)
var validated = false;
$(document).ready(function(){
$("#rfq").submit(function(event) {
if (validated === true) {
return true;
}
event.preventDefault(); // prevent submission
var email = $('#email').val();
if(email.indexOf("#") == -1){
$("#email").addClass('invalid');
return;
}
validated = true;
return $(this).trigger('submit');
});
});
You could try using this function to validate your address.
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
And then modify your code to submit the form.
$('#submit').click(function() {
var email = $('#email').val();
if(!validateEmail(email)){
$("#email").addClass('invalid');
}
else {
$("form").submit();
}
});

Categories

Resources