Form Field Submission - javascript

I have my HTML and JS, how would I use this form in my JS so if one of the fields are not entered, the form doesnt submit and shows me my original please enter all fields error
Form:
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
HTML:
<!doctype html>
<html lang="en">
<head>
<title> Forms </title>
<style>
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
</style>
<meta charset="utf-8">
<script src="prototype.js"></script>
<script src="forms.js"></script>
</head>
<body>
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value=""
placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="submit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</body>
</html>
JS:
function reset(){
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function submit(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(inp1 == "" || inp2 == "" || inp3 == "")
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
}
}

change your function name submit() to another because it conflict with builtin JS function, doing onclick="submit()" is same with this.form.submit() or document.getElementById('myForm').submit();
function reset() {
document.getElementById('input1').value = "";
document.getElementById('input2').value = "";
document.getElementById('input3').value = "";
document.getElementById('ErrorMessage').innerHTML = "";
}
function checkSubmit() {
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if (inp1 == "" || inp2 == "" || inp3 == "") {
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
} else {
//do your code here
document.getElementById('ErrorMessage').innerHTML = "submitting form";
document.getElementById('myForm').submit();
}
}
span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button {
margin-left: 10px;
}
body {
width: 80%;
margin: auto;
font-family: sans-serif;
border: 1px solid black;
}
<h1> Keyboard Events and Form Submit </h1>
<!-- Form -->
<form id="myForm" action="https://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<p> <span>Name:</span> <input id="input1" value="" placeholder="Enter Name" name="Name"></p>
<p> <span>Id:</span> <input id="input2" value="" placeholder="Enter ID" name="ID"></p>
<p> <span>Email:</span> <input id="input3" value="" placeholder="Enter Email" name="Email"></p>
<p>
<button id="submitButton" type="button" onclick="checkSubmit()"> Submit </button>
<button id="resetButton" type="button" onclick="reset()"> Reset </button>
</p>
<p style="color:red" id="ErrorMessage"> </p>
</form>

Change button type to "submit" and do validation in onsubmit event handler:
<form onsubmit="return validateMethod()" />
Move all your validation logics into validateMethod, return false if the validation is failed.
Below is an example but I think you should use a jquery lib for this:
function validateMethod(){
var inp1 = document.getElementById('input1').value;
var inp2 = document.getElementById('input2').value;
var inp3 = document.getElementById('input3').value;
if(!inp1 || !inp2 || !inp3)
{
document.getElementById('ErrorMessage').innerHTML = "Please enter all fields";
return false;
}
else{
//do your code here
document.getElementById('ErrorMessage').innerHTML = "";
return true;
}
}

You could simply use document.getElementById('myForm').addEventListener('submit', () => submit());
But you need to change <button id="submitButton" type="button" onclick="submit()"> Submit </button> to <button id="submitButton" type="submit"> Submit </button> (as Barmar said) and you also need to close your <form> tag.

Upon button click of the submission button you can iterate over all the input fields, determine whether or not they have the attribute required and then determine whether or not their value is an empty string (!field.value)
We put this in a try/catch block so that if a field is required and does not have a value, we can break out of the forEach loop by throwing an error and displaying the message Please Enter All Required Fields
let submit = document.querySelector("button");
submit.addEventListener("click", submitFn);
function submitFn() {
try {
document.querySelectorAll("form input").forEach(function(field) {
if (field.hasAttribute("required") && !field.value) {
throw error("not all fields filled in");
}
});
alert("all required fields filled in!")
} catch {
alert("please enter all required fields");
}
}
<form>
<label>first name </label><input required/>
<br/>
<label>last name</label><input required/>
<br/>
<label>email ( not required )</label><input />
<hr>
<button type="button">submit</button>
</form>
Note: It would be better code if you changed the type of the submit button to submit and changed the event from the above code from click to submit, but I've no idea if there was a reason for your markup or not so I leave that to your discretion.

Related

How do you make a button appear when you press an <input> in HTML? How do you make a button that adds text in HTML?

I am making a registration form. I have finished making the registration form, but I just need to add one more thing to the registration form: a button that adds text to the registration form. How do I make that button appear in the text input? Can someone help? Here is a runnable current snippet of the registration form:
function ValidationForm() {
let username = document.forms["RegForm"] ["Name"];
let email = document.forms ["RegForm"] ["Email"];
let phoneNumber = document.forms ["RegForm"] ["Telephone"];
let pass = document.forms ["RegForm"] ["Password"];
if (username.value == "") {
alert("Please enter your name.");
username.focus();
return false;
}
if (email.value == "") {
alert("Please enter a valid email address.")
email.focus();
return false;
}
if (phoneNumber.value == "") {
alert("Please enter your telephone number.")
phoneNumber.focus();
return false;
}
if (pass.value == "") {
alert("Please enter your password.")
pass.focus();
return false;
}
return true;
}
.regform {
margin-left: 70px;
font-weight: bold;
text-align: left;
font-family: sans-serif, bold, Arial, Helvetica;
font-size: 14px;
}
.buttons {
display: flex;
align-items: center;
width: 100%;
}
div input {
margin-right: 10px;
}
form {
margin: 0 auto;
width: 600px;
}
form input {
padding: 10px;
}
form label {
display: block;
width: 100%;
margin-bottom: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form</title>
<script src="script.js" defer></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h2 style="text-align: center;"> Registration Form </h2>
<form name="RegForm" action="hidden for no hackers" onsubmit="return ValidationForm()" method="POST" class="regform">
<div>
<label for="Name">Name:</label>
<input type="text" id="Name" size="60" name="Name">
</div>
<br>
<div>
<label for="E-mail">E-mail Address:</label>
<input type="email" id="E-mail" size="60" name="Email">
</div>
<br>
<div>
<label for="Password">Password:</label>
<input type="password" id="Password" size="60" name="Password">
</div>
<br>
<div>
<label for="Telephone">Telephone:</label>
<input type="tel" id="Telephone" size="60" name="Telephone">
</div>
<br>
<div class="buttons">
<input type="submit" value="Send" name="Submit">
<input type="reset" value="Reset" name="Reset">
</div>
</form>
</body>
</html>
Here is a "button that adds text":
document.getElementById("btn").addEventListener("click", () => {
document.getElementById("input").value += "Text";
});
<button id="btn">Click to add text to input below</button>
<br /><br />
<input id="input" />

JavaScript Radio Buttons not working and need assistance

function validateStudent() {
//retrieve Last Name, First Name, Email values
var lastName = document.getElementById("lastName").value;
var firstName = document.getElementById("firstName").value;
var email = document.getElementById("email").value;
var resident = document.getElementById("resident").value;
//retrieve index value of Advisor
advisorIndex = document.getElementById("advisor").selectedIndex;
//Validate and determine class value
classChecked = false;
for (var i = 0; i < document.frmStudent.class.length; i++) {
if (document.frmStudent.class[i].checked == true) {
classChecked = true;
vClass = document.frmStudent.class[i].value;
}
}
//Determine resident status
if (document.getElementById("resident").checked == true) {
alert("KY Resident:Yes.")
resident = "Yes";
} else {
alert("KY Resident:No.")
resident = "No";
}
//Validate student data entries
if (lastName == "") {
alert("Please enter your last name.");
document.frmOrder.lastName.select();
return false;
} else if (firstName == "") {
alert("Please enter your first name.");
document.frmOrder.firstName.select();
return false;
} else if (email == "") {
alert("Please enter a valid email address");
document.frmOrder.email.select();
return false;
} else if (classChecked == false) {
return false;
} else if (advisorIndex == -1) {
return false;
} else {
//determine Advisor name based on advisor index value
vAdvisor = document.frmStudent.advisor.options[advisorIndex].value;
//Prepare and display student entries
studentEntries =
alert(studentEntries);
return false;
}
}
fieldset {
width: 50%;
margin: 0px 0px 10px 1%;
}
legend {
padding: 2px;
text-indent: 5px;
}
p {
margin-left: 1%;
}
#contactEntry label {
clear: left;
display: block;
float: left;
width: 30%;
margin: 7px 5px;
}
#contactEntry input {
display: block;
float: left;
width: 60%;
margin: 7px 5px;
}
input[type="submit"],
input[type="reset"] {
display: inline;
float: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>EKU Student Information</title>
</head>
<body>
<form name="frmStudent" id="frmStudent" action=" " method="post" onsubmit="return validateStudent();">
<fieldset id="contactEntry">
<legend>Contact Information</legend>
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" />
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" />
<label for="email">E-Mail:</label>
<input type="text" name="email" id="email" />
</fieldset>
<fieldset id="fieldClass">
<legend>Class Classification</legend>
<input type="radio" name="class" id="freshman" value="Freshman" checked="checked" /> Freshman
<br/>
<input type="radio" name="class" id="sophomore" value="Sophomore" checked="checked" /> Sophomore
<br/>
<input type="radio" name="class" id="junior" value="Junior" checked="checked" /> Junior
<br/>
<input type="radio" name="class" id="senior" value="Senior" checked="checked" /> Senior
</fieldset>
<fieldset id="fieldAdvisor">
<legend>My Advisor</legend>
<select size="5" name="advisor" id="advisor">
<option>Mike Hawksley</option>
<option value="Chang-Yang Lin">CY Lin</option>
<option>Steve Loy</option>
<option>Bob Mahaney</option>
<option>Ted Randles</option>
</select>
</fieldset>
<p> <input type="checkbox" name="resident" id="resident" />
<label for="resident">Kentucky Resident</label>
</p>
<p><input type="submit" value="Submit" onclick="onsubmit" />
<input type="reset" value="Reset" /></p>
</form>
</body>
</html>
I'm tasked with the below and I'm issues getting the code to work. All help is greatly appreciated.
Create a form validation function that confirms that the user:
Enters values in the Last Name, First Name, and Email.
Specifies a Class value by selecting one of the Class radio buttons.
Selects an Advisor from the form selection list.
If any of the validation fail, display an alert with an appropriate message. If one of the text input values is not entered, select the current value of the associated input.
Call the form validation function using a form onsubmit even handler.
After the form validates all of the form inputs, display the alert to summarize the user inputs. If the Kentucky resident check box is checked, display the message "KY Resident: Yes." If the Kentucky resident check box is cleared, display the message "KY Resident:No."
By looking at your code I can see that the resident condition doesn't close.
Ex.:
{
alert("KY Resident:Yes.")
resident = "Yes";
}
else
{
alert("KY Resident:No.")
resident = "No";
{
change it to
if (document.getElementById("resident").checked == true)
{
alert("KY Resident:Yes.")
resident = "Yes";
}
else
{
alert("KY Resident:No.")
resident = "No";
}
To make your code loop through your form validator, I suggest to replace the <p><input type="submit" value="Submit" onclick = "onsubmit"/> to <p><input type="submit" value="Submit" onclick = "validateStudent"/>
For the array, you can create it at the start of your validateStudent function and in a condition you can push the message.
function validateStudent() {
var output = [];
// change these kind of if statement
if (document.getElementById("resident").checked == true) {
alert("KY Resident:Yes.")
resident = "Yes";
}
// to something like this
if (document.getElementById("resident").checked == true) {
output.push("KY Resident:Yes.");
resident = "Yes";
}
// at the end of the function
alert(output.join('\n'))
}

Why my text is printed on page and soon disappears in js

this is my code
i was trying to make a signup form and i made a script
i jst tried that the username should contain both alphabets and numbers and nothing else
if this condition is true than it continues
else it will give an error message displayed jst below it
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" onclick="store()" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
}
}
</script>
</body>
</html>
for eg when i keep the username field empty and click on submit the error which is to be displayed comes below it but it soon disappears.
i dont know the reason for it.
you will have to set the store in onsubmit event and not on the submit button onclick event because,onclick will execute the function and submit the form as well.
here is fiddle
execute function before submit
<html>
<head>
</head>
<body>
<style>
#sign_up_details {
padding: 10px;
}
</style>
<form name="sign_up_details" onsubmit="return store()">
<h3>Enter your details below</h3>
<input type="textbox" id="username" placeholder="Enter your desired username" />
<p id="usrnm_check"></p><br>
<input type="password" id="password" placeholder="Enter your desired password" />
<p id="pass_check"></p><br>
<input type="textbox" id="email" placeholder="Enter your email id" />
<p id="email_check"></p><br>
<input type="submit" name="submit" value="Submit" />
</form>
<script>
var usrnm = document.getElementById("username");
var pass = document.getElementById("password");
var email = document.getElementById("email");
var usrnm_check = document.getElementById("usrnm_check");
var pass_check = document.getElementById("pass_check");
var email_check = document.getElementById("email_check");
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
</body>
</html>
You can try something like this:
<form action="/dosomething.htm" method="GET" onsubmit="return store(this)">
[...]
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function store() {
var newReg = /^[A-Z]+[a-z]+[0-9]+$/
if (usrnm.value.match(newReg)) {
//next action here
return true;
} else {
usrnm_check.innerHTML = "Username should have alphabets and numbers";
return false;
}
}
</script>
Notice return true and return false statements in store() and in form onSubmit. If the store() will return false the form will not get submitted. At present your message goes away after display because your form gets submitted even if the validation fails.
Hope this helps!!

Why does the search button in my jsp code not work?

Following is the code of my jsp where there are two input fields regNo and studentName.
I want the user to enter only numbers in regNo field. It should not contain any spaces and the length of the digits should be only 12.
I added the check for characters and I added CSS and now my Search button isn't working.
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
#mycontainer, h1, h3 {
text-align:center;
}
form {
display:inline-block;
}
#errorMsgNumber {
display: none;
background: brown;
color: white;
}
</style>
<script>
var regNoField = document.getElementById('regNo');
var regNoMessage = document.getElementById('regNoErrorMsgNumber');
var inputFieldsButton = document.getElementById('inputFields');
regNoField.addEventListener('keydown', onChange);
function onChange(e) {
if (e.keyCode < 48 || e.keyCode > 57) {
regNoMessage.style.display = 'block'
};
if(/^\d+$/.test(regNoField.value)) {
inputFieldsButton.disabled = false;
} else {
inputFieldsButton.disabled = true;
}
}
$(document).ready(function(){
$('#inputFields').click(function(event){
if (document.getElementById('regNo').value !=""){
$("#number").submit();
}else if(document.getElementById('studentName').value !=""){
$("#name").submit();
}
});
});
</script>
</head>
<body>
<div id="mycontainer">
<form method="post" action="number" id="number">
<div id="regNoErrorMsgNumber">Only numbers are allowed</div>
<div style="text-align: center;" >
<!-- //TODO: Only number, no spaces, no special symbol and 12 digit check-->
<input width="20" type="text" data-validation="numbers" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"> OR
</div>
</form>
<form method="post" action="name" id="name">
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
</form>
</div>
<div style="text-align: center;">
<input id="inputFields" type="button" value="Search" />
</div>
</body>
I made little modification in your code. It was the ordering of javascript code. I have put your java script code after the elements. Now it will work.
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
#mycontainer, h1, h3 {
text-align:center;
}
form {
display:inline-block;
}
#errorMsgNumber {
display: none;
background: brown;
color: white;
}
</style>
</head>
<body>
<div id="mycontainer">
<form method="post" action="number" id="number">
<div id="regNoErrorMsgNumber">Only numbers are allowed</div>
<div style="text-align: center;" >
<!-- //TODO: Only number, no spaces, no special symbol and 12 digit check-->
<input width="20" type="text" data-validation="numbers" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"> OR
</div>
</form>
<form method="post" action="name" id="name">
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
</form>
</div>
<div style="text-align: center;">
<input id="inputFields" type="button" value="Search" />
</div>
</body>
<script>
var regNoField = document.getElementById('regNo');
var regNoMessage = document.getElementById('regNoErrorMsgNumber');
var inputFieldsButton = document.getElementById('inputFields');
regNoField.addEventListener('keydown', onChange);
function onChange(e) {
if (e.keyCode < 48 || e.keyCode > 57) {
regNoMessage.style.display = 'block'
};
if(/^\d+$/.test(regNoField.value)) {
inputFieldsButton.disabled = false;
} else {
inputFieldsButton.disabled = true;
}
}
$(document).ready(function(){
$('#inputFields').click(function(event){
if (document.getElementById('regNo').value !=""){
$("#number").submit();
}else if(document.getElementById('studentName').value !=""){
$("#name").submit();
}
});
});
</script>
You can do one more thing instead of referring the jquery from website itself you can refer the google hosting look at the link for the benefit http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/

How to revert change made by DOM?

So I made a simple javascript form validator which creates a box with the error message using DOM. But I can't figure out a way how to reset all these changes when i reset the form using
<button type="reset">
I would like to know how it's done please.
Thanks.
The Code
<html>
<head>
<script type="text/javascript">
function validate(){
var fname = document.getElementById("fname");
var surname = document.getElementById("surname");
if(fname.value === "" || fname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("fname").style.display = "block";
return false;
}
//Verify Last Name
if(surname.value === "" || surname.value === null){
document.getElementById("sbody").style.display = "block";
document.getElementById("surname").style.display = "block";
return false;
}
}//End Validate Function
</script>
<style type="text/css">
#sbody{
width: 100px;
height: 100px;
background-color: #f3f3f3;
display:none;
}
.vis{
display: none;
font-size: 12px;
}
</style>
</head>
<body>
<section id="sbody">
<span id="fner" class="vis">First Name is missing.</span>
<span id="lner" class="vis">Surame is missing.</span>
</section>
<form id="registerForm" method="POST" action="register.php" onsubmit="return validate()">
<label for="fname" class="labelStyle">First Name: </label>
<input id="fname" name="fname" type="text" value="">
<label for="surname" class="labelStyle">Surname: </label>
<input id="surname" name="surname" type="text" value="">
<button type="submit">Sign Up</button>
<button type="reset">Reset</button>
</form>
</body>
</html>
The browser cannot magically figure out what has to be done to reset the custom changes.
However you can listen to the reset event of the form using element.addEventListener.
DEMO
HTML
<form id="test">
<div id="errors-ct">The form has errors</div>
<button type="reset">Reset</button>
</form>
JS
//wait for the DOM to be ready
document.addEventListener('DOMContentLoaded', function () {
//store a reference to the errors container div
var errorsCt = document.getElementById('errors-ct');
//listen to the reset event of the form
document.getElementById('test').addEventListener('reset', function (e) {
var form = e.target; //this is how you could access the form
//hide the errors container
errorsCt.style.display = 'none';
});
});
If you want to reset the form, as if user hadn't made any selections or added any input, then just set all form element values to their default value, or empty.
jsFiddle
<div>
<form action="/echo/html" method="get">
<input type="text" placeholder="username" />
<br/>
<input type="password" placeholder="password" />
<br/>
<input type="checkbox" value="test" data-default="checked" checked="checked"/>
<br/>
<button type="reset" value="reset" onclick="resetForm()">reset</button>
<br/>
</form>
<div id="err">Some error message</div>
</div>
window.resetForm = function () {
var fields = $('input'),
uname, pass, check;
uname = $(fields.get(0));
pass = $(fields.get(1));
check = $(fields.get(2));
$("#err").text("");
uname.val('');
pass.val('');
if (check.attr("data-default") == "checked") {
check.attr("checked", "checked");
} else {
check.removeAttr("checked");
}
}

Categories