Solved

Javascript Form Validation not working

Posted on 2010-08-27
33
1,095 Views
Last Modified: 2013-11-11
Hi,
I have a page that has a jQuery Carousel, a Javascript rss news feed and a jQuery contact form
for that contact form, I have a javascript form validation, but it does not work.

Can someone tell me why?

 
<script type="text/javascript" language="JavaScript">
function checkform()
{
	if (document.getElementById("name").value = "") {
	return false;
	}

	else if (document.getElementById("email").value = "") {
	return false;
	}
	else if (document.getElementById("telno").value = "") {
	return false;
	}
	else if (document.getElementById("comment").value = "") {
	return false;
	}

	// If the script gets this far through all of your fields
	// without problems, it's ok and you can submit the form

	return true;
}

</script>

    
<script type="text/javascript"> 
 //Carousel Code
function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

jQuery(document).ready(function() {
    jQuery('#mycarousel').jcarousel({
        auto: 5,
        wrap: 'last',
		scroll: 1,
        initCallback: mycarousel_initCallback
    });
});
</script>
<script type="text/javascript">
$(function() {
	//trigger ajax on submit
	$('#contactForm').submit( function(){
		
		//hide the form
		$('#contactForm').hide();
		
		//show the loading bar
		$('.loader').append($('.bar')); 
		$('.bar').css({display:'block'});
		
		//send the ajax request  
		$.get('mail.php',{name:$('#name').val(), email:$('#email').val(), telno:$('#telno').val(), comment:$('#comment').val()},
	
		//return the data
		function(data){
			//hide the graphic
			$('.bar').css({display:'none'}); 
			$('.loader').append(data);  
		});	
	
		//stay on the page					
		return false;	
	});
});
</script>

<script type="text/javascript">
function InitClearBoxes() {
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("telno").value = "";
document.getElementById("comment").value = "";
}

window. onload = new Function("InitClearBoxes()");

</script>

<form id="contactForm" action="mail.php" method="post" name="contactForm" >     
    <div class="greyBox1">
      <div class="greyBoxHeadingRed">Contact Us</div>
    </div>
    	
    <div class="greyBoxMiddle"> 

<label>Name</label><br /><input class="textbox" type="text" name="name" id="name" value="" /><br />

<label>E-Mail</label><br /><input class="textbox" type="text" name="email" id="email" value="" /><br />

<label>Telephone</label><br /><input class="textbox" type="text" name="telno" id="telno" value="" /><br />

<label>Comments</label><br /><textarea class="textbox" name="comment" id="comment" rows="5" cols="19"></textarea><br />
<br />
<div id="note"></div>

    </div>
    <div class="greyBox3"><input  class="button" type="image" src="images/butt_sndemail.png" name="submit" value="Send Message" /></div>
</form>

Open in new window

0
Comment
Question by:cataleptic_state
  • 18
  • 14
33 Comments
 
LVL 4

Expert Comment

by:javaftper
ID: 33540233
I haven't had a chance to run your code but looking through it I would suggest there are four problems in your checkform() function.

You are attempting to run a comparison if statement for which you should be using the JavaScript equality operator (==).  However you are using the assignment operator (=) so your code will never get past the first statement.

== is the equal operator and returns a boolean true if both the operands are equal. JavaScript will attempt to convert different data types to the same type in order to make the comparison.

Suggest replacing lines 4 to 16 with-
if (document.getElementById("name").value == "") {
      return false;
      }

      else if (document.getElementById("email").value == "") {
      return false;
      }
      else if (document.getElementById("telno").value == "") {
      return false;
      }
      else if (document.getElementById("comment").value == "") {
      return false;
      }
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33541091
Ok that makes sense, but the page still submits
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33549319
In your provided code, you didn't call the checkform function.
Add

checkform();

before

//hide the form
$('#contactForm').hide();

but after

$('#contactForm').submit( function(){

Good luck!
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33565803
hi,
It does not seem to work.
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33567844
i cant get it to work via jQuery form validation plugin either, what am I doing wrong?
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33583642
My code here
Not finished.
<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript" language="JavaScript">

function checkform()

{

	if (document.getElementById("name").value == "") {

	document.getElementById("namecheck").innerHTML= "Please type something."

	}else{

document.getElementById("namecheck").innerHTML= "";

}



	if (document.getElementById("email").value == "") {

	document.getElementById("emailcheck").innerHTML= "Please type something." 

	}else{

document.getElementById("emailcheck").innerHTML= ""

}



	if (document.getElementById("telno").value == "") {

	document.getElementById("telcheck").innerHTML= "Please type something."

	}else{

document.getElementById("telcheck").innerHTML= ""

}



	if(document.getElementById("comment").value == "") {

	document.getElementById("commentcheck").innerHTML= "Please type something."

	}else{

document.getElementById("commentcheck").innerHTML=""

}



	// If the script gets this far through all of your fields

	// without problems, it's ok and you can submit the form



	return true;

}



</script>



    

<script type="text/javascript"> 

 //Carousel Code

function mycarousel_initCallback(carousel)

{

    // Disable autoscrolling if the user clicks the prev or next button.

    carousel.buttonNext.bind('click', function() {

        carousel.startAuto(0);

    });



    carousel.buttonPrev.bind('click', function() {

        carousel.startAuto(0);

    });



    // Pause autoscrolling if the user moves with the cursor over the clip.

    carousel.clip.hover(function() {

        carousel.stopAuto();

    }, function() {

        carousel.startAuto();

    });

};



jQuery(document).ready(function() {

    jQuery('#mycarousel').jcarousel({

        auto: 5,

        wrap: 'last',

		scroll: 1,

        initCallback: mycarousel_initCallback

    });

});

</script>

<script type="text/javascript">

$(function() {

	//trigger ajax on submit

	$('#contactForm').submit( function(){

	

		//hide the form

		$('#contactForm').hide();

		

		//show the loading bar

		$('.loader').append($('.bar')); 

		$('.bar').css({display:'block'});

		

		//send the ajax request  

		$.get('mail.php',{name:$('#name').val(), email:$('#email').val(), telno:$('#telno').val(), comment:$('#comment').val()},

	

		//return the data

		function(data){

			//hide the graphic

			$('.bar').css({display:'none'}); 

			$('.loader').append(data);  

		});	

	

		//stay on the page					

		return false;	

	});

});

</script>



<script type="text/javascript">

function InitClearBoxes() {

document.getElementById("name").value = "";

document.getElementById("email").value = "";

document.getElementById("telno").value = "";

document.getElementById("comment").value = "";

}



window. onload = new Function("InitClearBoxes()");



</script>



<form id="contactForm" action="mail.php" method="post" name="contactForm" >     

    <div class="greyBox1">

      <div class="greyBoxHeadingRed">Contact Us</div>

    </div>

    	

    <div class="greyBoxMiddle"> 



<label>Name</label><br /><input class="textbox" type="text" name="name" id="name" value="" onblur="checkform();"/><span id="namecheck"></span><br />



<label>E-Mail</label><br /><input class="textbox" type="text" name="email" id="email" value="" onblur="checkform();"/><span id="emailcheck"></span><br />



<label>Telephone</label><br /><input class="textbox" type="text" name="telno" id="telno" value="" onblur="checkform();"/><span id="telcheck"></span><br />



<label>Comments</label><br /><textarea class="textbox" name="comment" id="comment" rows="5" cols="19" onblur="checkform();"></textarea><span id="commentcheck"></span><br />

<br />

<div id="note"></div>



    </div>

    <div class="greyBox3"><input  class="button" type="image" src="images/butt_sndemail.png" name="submit" value="Send Message" /></div>

</form>



</head>

<body>

</body>

</html>

Open in new window

0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33584662
Trying to call this but the function does not work with my jQuery code. It opens it to another window and still submits.

0
 
LVL 6

Expert Comment

by:mickey159
ID: 33594390
Try to replace your code with mine and modify it to suit your needs.
You want to send your form with Ajax but it refreshes because you write
<form id="contactForm" action="mail.php" method="post" name="contactForm" >  
the action there triggers the event.
Maybe you should try
<form id="contactForm" method="post" name="contactForm" >  
Hope that helps.
For the jQuery validation plugin, it is used like this:
$("#form_id_here").validate();


Good luck!
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33605982
I'm sorry but you also need to insert the following code to get the jQuery validation working:


<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>

Open in new window

0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33609958
Hi,
this still does not work, it wont submit anything now.
please take a look at the page.

I even tried using spry textboxes but they do not work with the rest of the code


index.php
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33615591
You load 2 jQuery with prototype and they have conflics with each other.
Use
var something = jQuery.noConflict();
Then use jQuery like something.animate();
etc.
Try change the jQuery code to that and tell me the results.

Good luck!
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33615629
You also didn't change the form part.
change your form from <form> to </form> as shown below:

Good luck!
<form id="contactForm" action="mail.php" method="post" name="contactForm" >     

    <div class="greyBox1">

      <div class="greyBoxHeadingRed">Contact Us</div>

    </div>

    	

    <div class="greyBoxMiddle"> 

26 Viaduct St<br />

Vauxhall<br />

Birmingham<br />

B7 4HB<br />

<br />

0121 359 8807<br />

info@liquidprint.co.uk

<br /><br />



<label>Name</label><br /><input class="textbox" type="text" name="name" id="name" onblur="checkform();" value="" /><span id="namecheck"></span><br />



<label>E-Mail</label><br /><input class="textbox" type="text" name="email" id="email" onblur="checkform();" value="" /><span id="emailcheck"></span><br />



<label>Telephone</label><br /><input class="textbox" type="text" name="telno" id="telno" onblur="checkform();" value="" /><span id="telcheck"></span><br />



<label>Comments</label><br /><textarea class="textbox" name="comment" id="comment" onblur="checkform();" rows="5" cols="19"></textarea><span id="commentcheck"></span><br />

<br />

<div id="note"></div>



    </div>

    <div class="greyBox3"><input  class="button" type="image" src="images/butt_sndemail.png" name="submit" value="Send Message" /></div>

</form>

Open in new window

0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33616000
Hi,
the onblur check occurs, and the message is output.
But the page just reloads if the form is empty or if it has information inside and it has stopped submitting the emails.

Even when I remove this action="mail.php"

The page was working without any problems so I do not think it was a conflict
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33616056
Ok I added no conflict code, the page now sends an email but sents it when its blank too and it still loads in a new page, not within its own box and the loading bar does not come up
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33624770
I don't know whats up with the code, but I know that the attribute action is the target of the form.If you send the form, It will go to the action , in this case mail.php.

Good luck!
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33666866
I cant get it to work, I may have to use some other method or script
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 6

Expert Comment

by:mickey159
ID: 33669815
Are you going to use ajax to send the form?
This can help me to change the code.
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33669851
I found a good one and please read this:
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/

I will take time to modify your code so it works.

Good luck!
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33670294
Hey that looks really cool.

Ok, I will wait and see your mod.

Thanks
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33680151
How do you want to send your form?(Ajax or refresh)
I just need more information to finish it.
It seems there is problem in sending your form because I can't figure it out your way of sending.
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33680158
I am quite busy these weeks so please wait patien for the finished code.
Sorry!
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33689686
almost finished...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>

<meta http-equiv="Content-type" content="text/html; charset=utf-8" />



		<link rel="stylesheet" href="http://www.position-relative.net/creation/formValidator/css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" />

				<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>

			<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine-en.js" type="text/javascript"></script>

			<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine.js" type="text/javascript"></script>



		<script>

$(document).ready(function() {

			// SUCCESS AJAX CALL, replace "success: false," by:     success : function() { callSuccessFunction() }, 

			$("#contactForm").validationEngine({

				ajaxSubmit: true,

					ajaxSubmitFile: "mail.php",

					ajaxSubmitMessage: "Thank you, we received your inscription!",

				success :  false,

				failure : function() {}

			})

		});



		</script>

</head>

<body>

<form id="contactForm" action="mail.php" method="post" name="contactForm" >     

    <div class="greyBox1">

      <div class="greyBoxHeadingRed">Contact Us</div>

    </div>

    	

    <div class="greyBoxMiddle"> 

26 Viaduct St<br />

Vauxhall<br />

Birmingham<br />

B7 4HB<br />

<br />

0121 359 8807<br />

info@liquidprint.co.uk

<br /><br />



<label>Name</label><br /><input type="text" name="name" id="name" value=""  class="validate[custom[onlyLetter],length[0,100]] text-input" /><br />



<label>E-Mail</label><br /><input class="validate[required,custom[email]] text-input" type="text" name="email" id="email" value="" /><br />



<label>Telephone</label><br /><input type="text" name="telno" id="telno" value="" /><br />



<label>Comments</label><br /><textarea name="comment" id="comment"  rows="5" cols="19"></textarea><br />

<br />

<div id="note"></div>



    </div>

<input class="submit" type="submit" value="Validate & Send the form!"/>

</form>



</body>

</html>

Open in new window

0
 
LVL 6

Expert Comment

by:mickey159
ID: 33689810
I should be finished.
If you need ajax submit tell me.
Problems welcomed.
Change the <form> tag to below.
<form id="contactForm" action="mail.php" method="post" name="contactForm" >     

    <div class="greyBox1">

      <div class="greyBoxHeadingRed">Contact Us</div>

    </div>

    	

    <div class="greyBoxMiddle"> 

26 Viaduct St<br />

Vauxhall<br />

Birmingham<br />

B7 4HB<br />

<br />

0121 359 8807<br />

info@liquidprint.co.uk

<br /><br />



<label>Name</label><br /><input type="text" name="name" id="name" value=""  class="validate[required,custom[onlyLetter],length[0,100]] text-input" /><br />



<label>E-Mail</label><br /><input class="validate[required,custom[email]] text-input" type="text" name="email" id="email" value="" /><br />



<label>Telephone</label><br /><input type="text" class="validate[required,custom[onlyNumber]]" name="telno" id="telno" value="" /><br />



<label>Comments</label><br /><textarea class="validate[required]" name="comment" id="comment"  rows="5" cols="19"></textarea><br />

<br />

<div id="note"></div>



    </div>

<input class="submit" type="submit" value="Validate & Send the form!"/>

</form>

Open in new window

0
 
LVL 6

Expert Comment

by:mickey159
ID: 33689815
Add this to head to make it working.

Good luck!

<link rel="stylesheet" href="http://www.position-relative.net/creation/formValidator/css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" />

				<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>

			<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine-en.js" type="text/javascript"></script>

			<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine.js" type="text/javascript"></script>



		<script>

$(document).ready(function() { 

 $("#contactForm").validationEngine(



); 

})

</script>

Open in new window

0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33726075
Hi,
That does not work

I will link you the original script and then you can see why the problem is still happening.
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33732704
Can you give me the address so that I can test or have a look.
Is it still ok to use your original php attached here?
I will change that with the modified code.
Go http://w3schools.com/jquery/tryit.asp?filename=tryjquery_hide
Replace the left text field to the attached code below.
Then click the button above.
The results is on the right.
It should work,as least in my computer.
If it works, there is no problem in my code.
The problem is how to get all the stuff in your php.

Good luck!
<html>

<head>

<link rel="stylesheet" href="http://www.position-relative.net/creation/formValidator/css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>

<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine-en.js" type="text/javascript"></script>

<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine.js" type="text/javascript"></script>

<script>

$(document).ready(function() { 

 $("#contactForm").validationEngine(



); 

})

</script>

</head>

<body>

<form id="contactForm" action="mail.php" method="post" name="contactForm" >     

<div class="greyBox1">

<div class="greyBoxHeadingRed">Contact Us</div>

</div>    	

<div class="greyBoxMiddle"> 

26 Viaduct St<br />

Vauxhall<br />

Birmingham<br />

B7 4HB<br />

<br />

0121 359 8807<br />

info@liquidprint.co.uk

<br />

<br />

<label>Name</label><br /><input type="text" name="name" id="name" value=""  class="validate[required,custom[onlyLetter],length[0,100]] text-input" />

<br />

<label>E-Mail</label><br /><input class="validate[required,custom[email]] text-input" type="text" name="email" id="email" value="" />

<br />

<label>Telephone</label><br /><input type="text" class="validate[required,custom[onlyNumber]]" name="telno" id="telno" value="" />

<br />

<label>Comments</label><br /><textarea class="validate[required]" name="comment" id="comment"  rows="5" cols="19"></textarea>

<br />

<br />

<div id="note"></div>

</div>

<input class="submit" type="submit" value="Validate & Send the form!"/>

</form>

</body>

</html>

Open in new window

0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33768507
Hi,
I have removed ot off the site as it does not work. And I keep getting blank emails with no information.

I think I found the page where I got the script:

http://tutorialblog.org/how-to-create-your-own-ajax-contact-form/
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33776033
It's great that you found the solution.
Any problems please ask.

Good luck!
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33776851
Hi, no thats the current script I am using.

The problem is still there
0
 
LVL 6

Expert Comment

by:mickey159
ID: 33776970
So did you tested the script?
Can you give me an updated php?

THanks!
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33903115
Hi,
I havent tested it yet. I will try to do is later today.
I have been really busy. I am sorry for delay.
0
 
LVL 4

Author Comment

by:cataleptic_state
ID: 33903156
Sorry mickey, It does not work.

I am still able to send blank emails
0
 
LVL 6

Accepted Solution

by:
mickey159 earned 500 total points
ID: 33919761
I am sorry this is the new HTML code.
I forgot to change the jquery version to 1.4.2 which is the newest version.
This should work.
The blank email is not the validation problem.
Maybe you can give me the send page and the mail page.
Maybe the post variables are not correct.

Good luck!
<html>
<head>
<link rel="stylesheet" href="http://www.position-relative.net/creation/formValidator/css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine-en.js" type="text/javascript"></script>
<script src="http://www.position-relative.net/creation/formValidator/js/jquery.validationEngine.js" type="text/javascript"></script>
<script>
$(document).ready(function() { 
 $("#contactForm").validationEngine(

); 
})
</script>
</head>
<body>
<form id="contactForm" action="mail.php" method="post" name="contactForm" >     
<div class="greyBox1">
<div class="greyBoxHeadingRed">Contact Us</div>
</div>    	
<div class="greyBoxMiddle"> 
26 Viaduct St<br />
Vauxhall<br />
Birmingham<br />
B7 4HB<br />
<br />
0121 359 8807<br />
info@liquidprint.co.uk
<br />
<br />
<label>Name</label><br /><input type="text" name="name" id="name" value=""  class="validate[required,custom[onlyLetter],length[0,100]] text-input" />
<br />
<label>E-Mail</label><br /><input class="validate[required,custom[email]] text-input" type="text" name="email" id="email" value="" />
<br />
<label>Telephone</label><br /><input type="text" class="validate[required,custom[onlyNumber]]" name="telno" id="telno" value="" />
<br />
<label>Comments</label><br /><textarea class="validate[required]" name="comment" id="comment"  rows="5" cols="19"></textarea>
<br />
<br />
<div id="note"></div>
</div>
<input class="submit" type="submit" value="Validate & Send the form!"/>
</form>
</body>
</html>

Open in new window

0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
how to resize preview image 4 29
JavaScript error 1 33
jQuery Canlendar click function 5 20
Javascript generate change location 12 22
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now