I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here
Related
I want to know that in the following code, when I reference an element
by (document.getElementById) and make it equal to a variable for the validation purpose why I can't use the name instead of name1 in javascript.
function validation() {
name1 = document.getElementById('name');
if (name1.value == "") {
alert('this field cannot left empty');
return false;
}
}
<form id="form" action="message.html" method="post" onSubmit='return validation()' />
<input type="text" placeholder="enter your name" id='name' />
<input type="text" placeholder="address" id='address' />
<input type="tel" placeholder="telephone" id="telephone" />
<input type="submit" value="submit">
After adding var to name1 the code will start executing. After adding var you can assign the document.getElementById('name') to name also and it would work. You can run the below snippet for reference.
function validation(){
var name=document.getElementById('name');
if(name.value== ""){
alert('this field cannot left empty');
return false;
}
}
<form id="form" action="message.html" method="post"
onSubmit='return validation()'>
<input type="text" placeholder="enter your name" id='name' />
<input type="text" placeholder="address" id='address' />
<input type="tel" placeholder="telephone" id="telephone" />
<input type="submit" value="submit">
</form>
var name=document.getElementById('name');
You should use var before an element name.
Try using this..
You forgot to declare the variable.
If you are using a variable for assignment you must declare it before using.
For more reference you can look up this popular thread in SO, What is the purpose of the var keyword and when to use it (or omit it)?
function validation(){
var name = document.getElementById('name');
if(name.value== ""){
alert('this field cannot left empty');
return false;
}
}
I'm having to dip my toe back in the EE and javascript world after many years. What am I doing wrong here... a simple form being submitted, with a JS block to validate during the onsubmit event of the submit button. The alert("Here") message box does not appear when I submit the form, and the form gets submitted successfully, i.e. HelloForm gets displayed, with blank values, so I'm led to believe that validate() is not being called. I've tried this in both the Eclipse internal web browser as well as Chrome and see the same thing both times. I'm assuming that I don't need to explicitly activate javascript in either browser, as it would be on by default.
<html>
<head>
<script>
function validate()
{
alert("Here");
var x = document.forms["inputForm"].["first_name"].value;
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="inputForm" action="HelloForm" method="GET" onsubmit="return validate()">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit The Form" />
</form>
</body>
</html>
In this line will throw a syntax error:
document.forms["inputForm"].["first_name"].value
^^^
The statement is wrong, should be without dot between braces:
document.forms["inputForm"]["first_name"].value
//or
document.forms.inputForm.first_name.value
Working with Objects
You can use Html5 Validations.
<form name="inputForm" action="HelloForm" method="GET" >
First Name: <input type="text" name="first_name" required />
<br />
Last Name: <input type="text" name="last_name" required />
<input type="submit" value="Submit The Form" />
</form>
Working Demo
I'm trying to create a form with different inputs, input validation error receiving text, it does not validate (I want to be just text). The code is:
<form action="" id="myform" name="checkform" onsubmit="return validateform()" method="post">
<label for='Name'>Name:</label>
<input type="text" name="name" id="name"><br>
<label for='Surname'>Surname:</label>
<input type="text" name="surname" ><br>
<input type="submit" name="submit" value="Submit">
</form>
The javascript is:
function validateform(){
if(document.checkform.name.value == ""){
window.alert("Please insert your name.");
document.checkform.name.focus();
return false;
}
var nameText = document.forms["myform"]["name"].value; /* here is the problem :-( */
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
alert("Insert just letters !!!");
return false;
}
}
function validateform() {
var nameTxtBx = document.checkform.name,
name = nameTxtBx.value; //<-- added this line
if (name == "") {
alert("Please insert your name.");
nameTxtBx.focus();
return false;
}
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
alert("trebue doar litere");
return false;
}
return true; //<-- added this line
}
<form action="" id="myform" name="checkform" onsubmit="return validateform()" method="post">
<label for='Name'>Name:</label>
<input type="text" name="name" id="name">
<br>
<label for='Surname'>Surname:</label>
<input type="text" name="surname">
<br>
<input type="submit" name="submit" value="Submit">
</form>
You have typo in your variable, You just rename your variable nameText into name or vice versa.
var nameText = document.forms["myform"]["name"].value;
^^^^^^^
if (!name.match(/^\s*[A-Za-z]+\s*$/)) {
^^^^
Named form controls are made members of the form using their name. So even though the form has a name property, because your form also has a control with a name of name, then form.name references the control, not the form's name property.
Similarly, having a control with a name of submit means that you can't call the form's submit method, because form.submit references the control, not the method. So you should use control names that don't clash with standard form properties. Also, it's rare to require an ID for form controls since they can be referenced as properties of the form.
Lastly, it is handy to pass a reference to the form from the listener using this, then you don't need an ID on the form either. Consider:
<form onsubmit="return validateform(this)" ... >
Name: <input type="text" name="firstName"><br>
Surname: <input type="text" name="surname"><br>
<input type="submit" value="Submit">
</form>
Then in the function:
function validateform(form) {
Get the value of the firstName control once:
var firstName = form.firstName.value;
Now do the tests:
if (firstName == "") {
window.alert("Please insert your first name.");
form.firstName.focus();
return false;
}
It's more appropriate to use test than match if you want to test for a pattern rather than find all the matches:
if (!/^\s*[A-Za-z]+\s*$/.test(firstName)) {
alert("Insert just letters !!!");
return false;
}
}
I would like to know how can I change the AlertBox into a div.
I want the alertBox message to appear next to the input but in a div.
Thank You.
This is my Form input code:
<form name="form" action="gigi.php" method="POST" onsubmit="return validateForm()">
<input type="hidden" name="action" value="submit">
First Name:<br>
<input name="name" type="text" size="30"/><br>
Last Name:<br />
<input name="lname" type="text" size="30"/><br>
Email:<br>
<input name="caca" type="text" size="30"/><br>
Your message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input class="submit" type="submit" value="Send email"/>
</form>
And this is First Name input code in JavaScript:
function validateForm(){
var x=document.forms["form"]["name"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
In your HTML add something like:
<div id="form-errors"></div>
Then in JS, you can do that:
var alertDiv = document.getElementById('form-errors');
if (!x || x == '') {
alertDiv.textContent = 'First name must be filled out!';
}
Readings:
textContent
Similar question
Your question is about forms ? Since HTML5 you can simply write required on the input tab and it won't validate until you write some data.. you can then sanitize it.
In addition to Ramy's response, you can add jquery hide/show effects to display and hide the div element.
Also, do not forget to add style "z-index" to the div, so that it will appear on above other content of web-page.
My Javascript code:
if (valid == false){
alert(errmsg);
return false;
}else {
var success = "Name: "+fname+" "+lname+"\n"+
"Email: "+email+"\n"+"Address: "+adr1+", "+adr2+","+
adr3+" "+zip;
alert(success);
}
all that pops up is a blank alert window.
any help or insight would be greatly appreciated.
I'm kinda new to this, let me know if you need clarifications
heres my html portion of the code
<form id="contactInfo" action="">
<p class="name">
<span class="nameHead">Name</span>
<br />
First:
<input type="text" name="fname" id="fname" />
Last:
<input type="text" name="lname" id="lname" />
</p>
<p>
Email:
<input type="text" name="email" id="email" size="55" />
<p class="address">
<span class="addressHead">Address</span>
<br />
Street:<input type="text" name="street" id="adr1" />
<br />
City: <input type="text" name="city" id="adr2"/>
<br />
State:<input type="text" name="state" id="adr3" size="2" maxlength="2"/>
<br />
ZIP Code: <input type="text" name="zipCode" id="zip" size="10" maxlength="10"/>
</p>
<p>
<input type="submit" value="Submit" onclick="return validate();" />
<input type="reset" value="Reset" />
</p>
</form>
if the user enters name, city, zip, and email wrong (searched for patterns) so my if statements look like this
if (adr1 == ''){
errmsg = errmsg + "Street address is blank\n";
valid = false;
focusA1.focus();
focusA1.select();
}else if(adr1S == -1){
errmsg = errmsg + "Street address should be in the form of digits followed by letters\n";
valid = false;
focusA1.focus();
focusA1.select();
}
if valid ends up being false at the end of the function the errmsg shows up with what is wrong and focuses on that portion of the form. One thing problem i did end up running into is that whenever the page loaded the form would automatically submit. would it have anything to do with this?
<body onload= "rotate()">
<img src="images/a.jpg" name="banner" class="banner" />
code for a rotating banner?
The way I have it set up is to show another alert for when all form fields are entered correctly and when i do enter them correctly no alert shows up
in your validation function try some thing like this
function validation()
{
var valid == true;
if(cond1)
{
alert(cond1fails);
valid=false;
}
if(cond2)
{
alert(cond2fails);
valid=false;
}
.... and so on on to all the conditions .....
// then in the last line
return valid;
}
try this it should simply work