forms and getElementById - javascript

I am having issues using getElementById in a form. I have tried several ways with no luck. I basically need the form to verify that both First Name and Last Name fields are filled in, and display a popup box with the names displayed.
Below is the code I have tried. I tried 2 different ways in my javascript and I am not sure what I am missing.
<form name="form" id="form" method="post" action="">
<p class="FirstName">
<label for="FirstName">First Name:</label>
</p>
<p>
<input name="FirstName" type="text" id="FirstName" />
</p>
<p class="LastName">
<label for="LastName">Last Name:</label></p>
<p>
<input name="LastName" type="text" id="LastName" />
</p>
<p class="submit">
<input name="getName" type="button" id="getName" value="Get Name" onClick=ā€¯getName();" />
</p>
</form>
var getName = function () {
if (document.getElementById("FirstName").value == "" || document.getElementById("LastName").value == "") {
return ("Please enter a first name and a last name.");
} else {
var FullName = document.getElementById("FirstName").value + ' ' + document.getElementById("LastName").value;
return FullName;
}
}
function getName() {
var FullName = document.getElementById('FirstName');
document.getElementById('LastName');
if (FullName.value != "")
alert(FullName.value)
else
alert("Please enter first and last name")
}

The first way you tried was the right one.
The problem is, you're not binding the onclick event to a function.
You declare the getName function in the head tag, interpreted before the body tag.
But you overwrite getName when declaring the button input with its id and name set to getName.
You can just change its id and name to submitButton for example. You could also move the function declaration to the end of the body tag, or wrap it in an onLoad method.
I wrapped the getName call in an alert to see the result (alert(getName()))
Check out the jsFiddle : http://jsfiddle.net/zpNSv/1/
<form name="form" id="form" method="post" action="">
<p class="FirstName">
<label for="FirstName">First Name:</label>
</p>
<p>
<input name="FirstName" type="text" id="FirstName" />
</p>
<p class="LastName">
<label for="LastName">Last Name:</label>
</p>
<p>
<input name="LastName" type="text" id="LastName" />
</p>
<p class="submit">
<input name="submitButton" type="button" id="submitButton" value="Get Name" onClick="alert(getName())" />
</p>
</form>
AND JS
function getName() {
var FirstName = document.getElementById("FirstName"),
LastName = document.getElementById("FirstName");
if (FirstName.value == "" || document.getElementById("LastName").value == "")
{
return ("Please enter a first name and a last name.");
}
else
{
var FullName = FirstName.value + ' ' + LastName.value;
return FullName;
}
}

Take a closer look at this line, you are doing nothing with the last statement
var FullName = document.getElementById('FirstName'); document.getElementById('LastName');
You have 2 getName. only one can live.
function getName(){
var firstName = document.getElementById("firstName").value;
var lastName= document.getElementById("lastName").value;
if(firstName === "" || lastName === ""){
alert("You need to fullfield both First Name and Last Name");
}
}else{alert("This work.");}

Related

Form Validation not responding correctly

I wrote a simple script to check my form data upon submission. However it's not supposed to keep sending if the inputs are empty. Why isn't it working?
<script src="scripts/formvalidate.js"></script>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" id="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" id="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" id="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" id="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var result = false;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementById("label").innerHTML = output;
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
result = true;
}
return result;
}
You can't use multiple elements with the same id's since an Id is supposed to identify a uniquely an element of the page (HTML5 Specification says: ID must be document-wide unique.), try to use classes instead, and change your getElementById() to getElementsByClassName() just like this and it should work fine:
function formValidate() {
var form = document.forms["form"];
var name = form.elements["name"].value;
var email = form.elements["email"].value;
var subject = form.elements["subject"].value;
var message = form.elements["message"].value;
var output = "*";
var required = "Required";
var asterisk = "* ";
if (name == "" || email == "" || subject == "" || message == "") {
document.getElementsByClassName("label").innerHTML = output; //notice how I changed the function used here
document.getElementById("asterisk").innerHTML = asterisk;
document.getElementById("required").innerHTML = required;
alert('Please fill out all fields');
return false;
}
else {
alert('Thanks for contacting me');
return true;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="formvalidate.js"></script>
<title></title>
</head>
<body>
<h3 id="required">Contact Me</h3>
<form name="form" onsubmit="return formValidate()" method="POST">
<label for="name">Name<span id="asterisk" class="label"></span></label>
<input type="text" id="name" name="name">
<label for="email">Email<span id="asterisk" class="label"></span></label>
<input type="email" id="email" name="email">
<label for="subject">Subject<span id="asterisk" class="label"></span></label>
<input type="text" id="subject" name="subject">
<label for="message">Message<span id="asterisk" class="label"></span></label>
<textarea name="message" id="message"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</body>
</html>
Note that the asterisk you try to insert, is only inserted in one input for the same reason noted before (multiple ID's are senseless to the DOM). as the DOM tries to fix that, it only get's the first element on the document with the given id (to fix it just change id="asterisk" types to class="asterisk" type).
Plot twist: the reason you probably didn't see any error screen was because (I guess) you were testing it on chrome, which only shows the error for a millisecond. my personal advise is to use firefox for testing purposes, since it won't hide any error at all.

How can i validate <input type = "date"> and <textarea></textarea> tag using javascript

When i try to validate Institute name and date of birth in my html form using javascript it is not working, i searched alot in google but i am not able to reach to the solution of my queries. Any type of help is appreciated.
function validation() {
var first_name = document.getElementById('Fname').value;
var last_name = document.getElementById('Lname').value;
var Institute_name = document.myForm.institute.value;
var DOB = document.getElementById('dob').value;
if (first_name == "") {
document.getElementById('fname').innerHTML = "** Please fill this field";
return false;
}
if ((last_name == "") && (first_name != "")) {
document.getElementById('lname').innerHTML = "** Please fill this field";
document.getElementById('fname').innerHTML = "";
return false;
}
if ((Institute_name == '') && (last_name != "")) {
document.getElementById('InstituteE').innerHTML = "** Please fill this field";
document.getElementById('branchE').innerHTML = "";
return false;
}
if (!DOB.value) {
document.getElementById('DateOfBirth').innerHTML = "Please enter a valid birthday";
return false;
}
}
<body>
<div id="container">
<div id="wall">
<form action="" name="myForm" onsubmit="return validation()" method="POST" class="bg-light">
<h1 style="text-align: center; font-size: 52px; color: bisque"><u>INTERNSHIP FORM</u></h1><br><br>
<p>FIRST NAME : <input type="text" id="Fname" placeholder="First Name......" autocomplete="off">
<span id="fname" class="text-danger"></span> LAST NAME : <input type="text" id="Lname" placeholder="Last Name........" autocomplete="off">
<span id="lname" class="text-danger"></span>
</p>
<p>
NAME OF THE INSTITUTE :
<br><br>
<textarea name="institute" rows="3" cols="30" placeholder="Institute name...">
</textarea>
<span id="InstituteE" class="text-danger"></span> DATE OF BIRTH : <input type="date" id="dob" autocomplete="off">
<span id="DateOfBirth" class="text-danger"></span> </p>
<p>
<input type="submit" name="submit" value="SUBMIT" class="btn btn-success" style="padding: 20px; font-size: 28px;">
<input type="reset" name="reset" value="RESET" class="btn btn-primary" style="padding: 20px; font-size: 28px;">
</p>
</form>
<br><br><br><br><br><br>
</div>
</div>
</body>
</code>
Here I am using span tag to print the error of not filling that field, and made this tag's class = "danger".
I found 2 issues when I tried it with your code.
Textarea: - your textarea already contains spaces after loading - so when you check if it's empty, it will find content and therefore it's "filled"
(Institute_name == '')
So I would recommend to remove leading and trailing white spaces first, so only the "real content" will be checked (the js method trim will do this for you)
( Institute_name.trim() == '')
Date:
When you access the date field
var DOB = document.getElementById('dob').value;
you already get the value (e.g. 2018-09-22). So accessing the value twice
if(!DOB.value)
will always evaluate to undefined / false. So just check the variable again for e.g. empty string
if(DOB == '')
Beside that you can always check if it's a valid date input (see Detecting an "invalid date" Date instance in JavaScript)
Btw. I would recommend to look into Developer/Dev Tools of yor preferred browser - It really helps you to debug js code, inspect variables, etc. :-)

How to check whether an email address contains an # sign and a '.'. in html and javascript

I'm performing some validation checks on some inputs from the user. I was wondering how do I check that the email entered by the user contains an # symbol and a '.' as well as characters before and after the # symbol. Thanks in advance for answering.
<!DOCTYPE html>
<html>
<head>
<script language="JavaScript">
function showInput() {
var comment = document.getElementById("com").value;
var first = document.getElementById("fname").value;
var last = document.getElementById("lname").value;
var dateOfVisit = document.getElementById("date").value;
var firstError = document.getElementById('firstNameError');
var lastError = document.getElementById('lastNameError');
var displayEl = document.getElementById('displayname');
if (!first) {
firstError.setAttribute('style', 'display: block; color: red');
} else {
firstError.setAttribute('style', 'display: none;');
}
if (!last) {
lastError.setAttribute('style', 'display: block; color: red');
} else {
lastError.setAttribute('style', 'display: none;');
}
displayEl.innerHTML =
first + " " + last + " visited this on " + dateOfVisit + " and said '" + comment || 'not a thing...' + "'";
}
</script>
<title>Great Pyramid of Giza</title>
</head>
<body>
<h2>Leave A Review!</h2>
<p>Have you been to this wonder of the world? If so, leave a review.</p>
<form>
First Name:<br>
<input type = "text" name="firstname" id="fname"><br>
<span style="display: none;" id="firstNameError">First name is required!</span>
Last Name:<br>
<input type = "text" name="lastname" id="lname"><br>
<span style="display: none;" id="lastNameError">Last name is required!</span>
Email Address:<br>
<input type = "text" name="email"><br>
Date of Visit:<br>
<input type = "text" name="date" id="date"><br>
Comment:<br>
<input type = "text" name="comment" size="70" id="com"><br>
</form>
<input type = "submit" value="Submit" onclick="showInput();">
<h2>Comments:</h2>
<p><span id='displayname'></span></p>
</body>
</html>
You can create a email input and validate against that instead of using any regex...
function isEmail(email) {
var input = document.createElement('input')
input.type = 'email'
input.value = email
return input.validity.valid
}
console.log(isEmail('admin#example.com'))
console.log(isEmail('#example.com'))
But why bother??? just use <input type="email"> and skip all javascript nonsens
<form>
<input type="text" name="firstname" required autocomplete="given-name">
<input type="text" name="lastname" required autocomplete="family-name">
<input type="email" name="email" autocomplete="email">
<input type="date" min="2018-04-21" name="date">
<textarea name="comment"></textarea>
<input type="submit">
</form>
ps, use form.onsubmit instead of btn.onclick (way better)
read more about constraint validation and inputs

Checking if the input fields are filled in properly (pure javascript)

I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.

Simple JavaScript validation not working?

Not sure why this isn't working.
<!DOCTYPE html>
<html>
<head>
<title>Player 1</title>
<link rel="stylesheet" type="text/css" href="playerOne.css">
</head>
<body>
<div id="heading">
<h>Player 1</h>
</div>
<form name="playerInfo" onsubmit="return validate()" method="post">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label id="inPID">Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus >
<br>
<br>
<label id="inFN">First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name" >
<br>
<br>
<label id="inLN">Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name" >
<br>
<br>
<label id="inEA">Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label id="inPW">Password:</label>
<br>
<input type="password" name="password" class="input" id="pass" >
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate" >
</fieldset>
<hr>
</form>
<div id="error"></div>
<script>
function testVal(){
return false;
}
function validate() {
var message;
var test = true;
message = document.getElementById("error");
message.innerHTML += "";
var x = document.getElementById("id");
if(x.value == ""|| x.value == null||x.value== "Player ID") {
x.style.backgroundColor = "#FF0000";
message.innerHTML += "Player ID is missing\n";
test = false;
}else{
}
var x = document.getElementById("fname");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "First name is missing\n";
test = false;
}else{
}
var x = document.getElementById("sname");
if(x.value == "") {
x.style.borderColor ="#FF0000";
message.innerHTML += "Surname is missing\n";
test = false;
}else{
}
var x = document.getElementById("email");
if(x.value == "") {
x.style.borderColor = "#FF0000";
message.innerHTML += "Email is missing\n";
test = false;
}else{
}
var x = document.getElementById("pass");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "Password is missing\n";
test = false;
}else{
}
return test;
}
</script>
</body>
So it should change the color of the borders to red if the input is incorrect( or empty), and inform the user in a div. For some reason, the code is always submitting without recognizing the errors. Also I'm a beginner at JavaScript (and html) so if anyone has any input on improving this code it would be appreciated.
EDIT: Apologies. I uploaded the wrong version of the code the testval function was only there to check if the onsubmit was working correctly, and the validate function is now called onsubmit, which is where/when it should be but is not working.
EDIT 2: Thank you for your help on the format and correct tag use. I have edited it as to your recommendations, however the actual validating (function) is still not working, despite the inclusion of quotation marks.
references:
http://www.w3schools.com/js/js_validation.asp
http://www.tutorialspoint.com/javascript/javascript_form_validations.htm
Look at your console errors.
First is a typo in testVal - "retrun" instead of "return".
Next up, strings need to be quoted so x.style.borderColor = #FF0000; needs to be x.style.borderColor = "#FF0000";
Beyond that, you don't actually seem to be calling validate() in the code provided. Also, look into using the placeholder attribute for input elements, or - possibly more appropriate - the label element, rather than your approach of putting the label inside the value of each input.
You gave the same name x for JavaScript variables. I also fixed your form a little.
Some suggestions:
The \n in a.innerHTML += "Some string\n" doesn't work. Use "<br />" instead
Different names for different variables please
Use the placeholder attribute instead of value to suggest the user
Use the message variable to hold the error message instead of setting the innerHtml directly because Javascript uses Pass By Value (see reference)
When you get more acquainted with Javascript, you would want to learn jQuery. It provides a great API for easier time coding as well as make Html traversal, event handling and Ajax much simpler. http://www.w3schools.com/jquery/default.asp is a great place to learn jQuery.
Fixed Javascript and Html:
function validate() {
var message = "";
var test = true;
var id = document.getElementById("id");
if (id.value == "" || id.value == null) {
id.style.backgroundColor = "#FF0000";
message += "Player ID is missing<br />";
test = false;
} else {
}
var fname = document.getElementById("fname");
if (fname.value == "" || fname.value == null) {
fname.style.borderColor = "#FF0000";
message += "First name is missing<br />";
test = false;
} else {
}
var sname = document.getElementById("sname");
if (sname.value == "" || sname.value == null) {
sname.style.borderColor = "#FF0000";
message += "Surname is missing<br />";
test = false;
} else {
}
var email = document.getElementById("email");
if (email.value == "" || email.value == null) {
email.style.borderColor = "#FF0000";
message += "Email is missing<br />";
test = false;
} else {
}
var x = document.getElementById("pass");
if (x.value == "" || x.value == null) {
x.style.borderColor = "#FF0000";
message += "Password is missing<br />";
test = false;
} else {
}
if (test == true) {
document.alert("OK");
// document.getElementById("frmPlay").submit();
} else {
document.getElementById("error").innerHtml = message;
}
}
<form name="playerInfo" onsubmit="validate()" method="post" id="frmPlay">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label>Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus>
<br>
<br>
<label>First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name">
<br>
<br>
<label>Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label>Password:</label>
<br>
<input type="password" name="password" class="input" id="pass">
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate">
</fieldset>
<hr>
</form>
<div id="error"></div>

Categories

Resources