Reputation: 4078
I have a form and below is code
And when submit is clicked it returns true
rather that displaying the
textfiled
to empty, it should give some error.
Its a simple form validation
html
<form name="rt-form2" method="post" onsubmit="return validateform();">
<input type="text" value="Name" name="name2" id="name1"><br>
<input type="text" value="Email" name="Email" id="Email1"><br>
<input type="text" value="Phone Number" name="phone" id="phone1"><br>
<input type="submit" value="submit" name="submitm" class="submit-btn">
</form>
and javascript validation
<script type="text/javascript">
function validateform(){
alert("Submit button is clicked");
if(document.rt-form2.name2.value.length < 1) {
alert("Enter name");
return false;
}
else {
alert("Submitting");
return true;
}
}
</script>
Upvotes: 0
Views: 86
Reputation: 23713
Try this:
<body>
<head>
<script type="text/javascript">
function validateform()
{
alert("Submit button is clicked");
var namelength = document.formulari.name2.value.length;
if(namelength < 1)
{
alert("Enter name");
return false;
}
else
{
alert("Submitting");
return true;
}
}
</script>
</head>
<form name="formulari" method="post" onsubmit="return validateform();">
<input type="text" name="name2" id="name2"><br>
<input type="text" name="Email" id="Email1"><br>
<input type="text" name="phone" id="phone1"><br>
<input type="submit" value="submit" name="submitm" class="submit-btn">
</form>
</body>
If by default you have a value in the field (value="Name"
) it won't launch the "empty" error. Because is getting that default value.
EDIT: I forgot to add that you have to chance the name of the form name. As I did in my code below.
Upvotes: 0
Reputation: 716
function validateForm()
{
var x=document.forms["formElem"]["name"].value;
if (x==null || x=="" || x=="Name")
{
alert("All fields must be filled out");
return false;
}
var x=document.forms["formElem"]["hnumber"].value;
if (x==null || x=="" || x=="Phone")
{
alert("All fields must be filled out");
return false;
}
var x=document.forms["formElem"]["mnumber"].value;
if (x==null || x=="")
{
alert("All fields must be filled out");
return false;
}
alert('Thanks for applying. Someone from HR will contact you shortly.');
}
This is a really simple script that I use.
Upvotes: 0
Reputation: 2469
I reran this and it seem that the error came from the name of the form. Using the '-' within the javascript was throwing errors. Once I switched to an '_' it seem to work fine.
I have done the same thing with jQuery that allows you to enter a default value and also validates all field with the class required
. It is only slightly more complex because it validates that default value has been changed and also clears the field when it is selected.
Upvotes: 1
Reputation: 766
Dude your script is correct. Just remove the hyphen from your form name and you're good to go!
Upvotes: 0