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;
}
}
Related
Please take a look at this code, I want to know how to validate all these input elements in this single form using JavaScript.
I know they look the same but i have the names in a separate div. Your corrections and contributions to my form will be very much appreciated.
<form name="myForm">
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="password" name="fname"><br><br>
<input type="submit" value="Submit">
</form>
Yes, You can. Try this to Validate data in Java Script
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
Then You have to create a javaScript Function to Validate the data as above validateDate(), for this, now your code is
<script>
function validateData() {
var fname = document.getElementById("fname").value;
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
//if name is empty
if(fname == "" || username == "" || email == "" || password == "") {
//SOme Error Code here
alert("Please Fill All the Form Data.");
}
if(username.length < 4 || username.length > 20) {
//SOme Error Code here
alert("username must be less than 20 but more than 4 Characters.");
}
// You can add more filters like password length, and so on by using more if conditions
}
</script>
<body>
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
That's all. :)
Even though this requires jQuery, it can solve your problem:
To use jQuery Validate you just need to include in your code a version of the jQuery library equal or more recent than 1.7 and a file with the plugin.
See an example:
jQuery('form').validate();
After calling the jQuery.fn.validate method, you can validate your fields using data attributes, that are valid to the HTML5, according to the W3C.
See a example to required field:
<form>
<input type="text" data-required />
</form>
https://plugins.jquery.com/validate/
I am trying to make it so that if the user does not enter their first and last name an alert message will occur. The code looks right to me but it is not working.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function func(){
var first = getElementByID("fname").value;
var last = getElementByID("lname").value;
var email = getElementByID("mail").value;
var phone = getElementByID("phone").value;
if ( first == "" && last =="")
{
alert("Please Enter First and Last Name");
}
</script>
</head>
<body>
<form id="survey" name="survey" method="post">
First Name:<br>
<input type="text" id="fname" name="fname"><br>
Last Name:<br>
<input type="text" id="lname" name="lname"><br>
Email:<br>
<input type="email" id="mail" name="mail"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit" onclick="func()">
</form>
</body>
use document.getElementById, not getElementByID
The if should use || (OR), not && (AND), so it alerts if either field is empty, not only when both fields are empty.
To keep the form from submitting, the validation function must return false, and the onclick attribute needs to return the value.
It's better to use the form's onsubmit handler than the submit button's onclick handler.
So the JS should be:
function func(){
var first = getElementByID("fname").value;
var last = getElementByID("lname").value;
var email = getElementByID("mail").value;
var phone = getElementByID("phone").value;
if ( first == "" && last =="") {
alert("Please Enter First and Last Name");
return false;
}
}
and the HTML should be:
<form id="survey" name="survey" method="post" onsubmit="return func()">
First Name:<br>
<input type="text" id="fname" name="fname"><br>
Last Name:<br>
<input type="text" id="lname" name="lname"><br>
Email:<br>
<input type="email" id="mail" name="mail"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit">
</form>
if ( first == "" && last =="")
implies that the warning will appear only if first AND last are empty.
Try using:
if ( first == "" || last =="")
use document.getElementById('fname'), not getElementByID
error in your condition, try it with (first == "" || last == "")
(first is empty OR last is empty) -> error
EDIT, code snippet, in your code, there is missing one } at the end of script!
function func(){
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var email = document.getElementById("mail").value;
var phone = document.getElementById("phone").value;
if ( first == "" || last =="")
{
alert("Please Enter First and Last Name");
return false;
}
return true;
}
<form id="survey" name="survey" method="post" onsubmit="return func();">
First Name:<br>
<input type="text" id="fname" name="fname"><br>
Last Name:<br>
<input type="text" id="lname" name="lname"><br>
Email:<br>
<input type="email" id="mail" name="mail"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit" value="submit">
</form>
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.
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
I've got the following "subscribe by e-mail" form:
<form style="border:1px solid #ccc;padding:3px;text-align:center;" action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=food101coil', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true">
<p>enter e-mail:</p>
<p><input type="text" style="width:140px" name="email"/></p><input type="hidden" value="food101coil" name="uri"/><input type="hidden" name="loc" value="en_US"/><input type="submit" value="SEND" /></form>
I want to move the "enter e-mail" section inside the form part. So that when the user clicks on it, the text will disappear.
Could someone please help me with how to do that?
The following code will do what you want, but also maintain an email once entered..
HTML
<input id="email" type="text" style="width:140px" name="email" value="enter e-mail"/>
JavaScript
<script type="text/javascript">
var emailfield = document.getElementById('email');
emailfield.onfocus = function(){
if (this.value == 'enter e-mail') this.value = '';
}
emailfield.onblur= function(){
if (this.value == '') this.value = 'enter e-mail';
}
</script>
Live example: http://www.jsfiddle.net/YS2Xm/
<input type="text" name="email" onclick="this.value='';" value="enter e-mail" />
Not tested, should work though!