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/
Related
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" />
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.
The code for the log in function should check for a match with the credentials that were entered, or alert the user that they entered invalid credentials. My code does neither, when i click the button, it doesnt work. Please let me know if i have made an error that i do not see. Thanks!
LOGIN CODE:
function addEvent() {
var snumber = document.getElementById('snumberE').value;
var pass = document.getElementById('passE').value;
var arr = JSON.parse(localStorage.getItem('profiles'));
for(var i=0; i<arr.lenght; i++) {
if(arr[i].password == pass && arr[i].snumber == snumber) {
window.open('StudentView.html');
} else {
alert('Please enter valid credentials or sign up');
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<script src='Login.js'></script>
<style>
#form1 {
position: relative;
float: left;
width: 600px;
}
#form2 {
position: relative;
float: center;
}
</style>
</head>
<body>
<h1 id=tru>Announcement App</h1>
<!--Navigation Bar-->
<ul>
<li>Login</li>
<li>Sign Up</li>
<li>Help</li>
</ul>
<fieldset id=form1>
<h2>Student Login</h2>
<form>
Student Number:
<input required id="snumberE" type="text" placeholder="Enter Student #"><br>
Password:
<input required id="passE" type="password" placeholder="Enter Password"><br>
<input type="submit" onclick='addEvent()' value='Login'>
</form>
</fieldset>
</body>
</html>
SIGNUP CODE
function clubslist() {
var clublist = document.getElementById('clubs');
var arr = JSON.parse(localStorage.getItem('clublist'))
for(i=0; i<arr.length;i++) {
var option = document.createElement("option");
option.text= arr[i];
option.value = arr[i]
clublist.add(option,clublist.options[null]);
}
}
function SignUp() {
var list = document.getElementById('clubs');
var selected = [];
var profiles = [];
var profile = {
fname: document.getElementById('firstname').value,
lname: document.getElementById('lastname').value,
snumber: document.getElementById('snumber').value,
gender: document.getElementById('gender').value,
grade: document.getElementById('grade').value,
clubs: selected,
password: document.getElementById('password').value,
rpassword: document.getElementById('1password').value
};
profiles.push(profile);
if(localStorage.getItem('profiles') == null) {
localStorage.setItem('profiles',JSON.stringify(profiles));
} else {
var pfiles = JSON.parse(localStorage.getItem('profiles'));
pfiles.push(profile);
localStorage.setItem('profiles', JSON.stringify(pfiles));
}
}
<!DOCTYPE html>
<html>
<head>
<title>Sign Up Page</title>
<script src='Signup.js'></script>
<style>
#field1 {
position: relative;
float: left;
width: 300px;
}
#field2 {
position: relative;
float: center;
width: 300px;
}
</style>
</head>
<body onload = 'clubslist()'>
<h1>Announcement App</h1>
<!--Navigation Bar-->
<ul>
<li>Login</li>
<li>Sign Up</li>
<li>Help</li>
</ul>
<h2>Sign Up</h2>
<fieldset id=field1>
<h3>Student Sign Up</h3>
<form tag="signupinfo">
First Name:
<input type="text" placeholder="Enter First Name" id="firstname" required><br>
Last Name:
<input type="text" placeholder="Enter Last Name" id="lastname" required><br>
Student Number:
<input id="snumber" type="text" placeholder="Enter Student Number" name="studentnumber" required><br>
Gender:
<select id=gender required>
<option value=male>Male</option>
<option value=female>Female</option>
</select><br>
Grade:
<select id=grade name="grade" required>
<option value="9">Grade 9</option>
<option value="10">Grade 10</option>
<option value="11">Grade 11</option>
<option value="12">Grade 12</option>
</select><br>
Clubs:<br>
<select id=clubs multiple></select><br>
Password:
<input id="password" type="password" placeholder="Enter Password" name="psw" required><br>
Repeat Password:
<input id="1password" type="password" placeholder="Repeat Password" name="psw-repeat" required><br>
<button type="submit" onclick="SignUp()" class="signupbtn">Sign Up</button>
</form>
</fieldset>
</body>
</html>
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");
}
}
Can anyone see where I could be making a mistake? The form text-box background colors are originally set to grey. If the user makes a mistake I want to turn them yellow with a red border. The function is sort of working, because the form is not going to the server when the form is filled out incorrectly. But the css doesn't change. If I comment out my js call it will post to the server. Here are the snippets:
CSS:
.invalid{
background-color:#ff9;
border: 2px red inset;
}
.reqd{
background-color:#222222;
color:#555555; border-style: solid;
border-color:#555555;
border-width: 1px;
}
HTML:
<!DOCTYPE html>
<?php
// Debug
error_reporting(E_ALL);
?>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/regauth.js"></script>
<title></title>
</head>
<body id="registerBody">
<section id="registerBox">
<form id="registerForm" method="post" action="regauth.php">
<p>Welcome to the atlas registraton! Please fill out the information below.</p>
<br>
<p><label for="firstName">First Name: <input type="text" size="30" id="firstName" name="firstName" class="reqd"></label></p>
<p><label for="lastName">Last Name: <input type="text" size="30" id="lastName" name="lastName" class="reqd"></label></p>
<p><label for="email">Email: <input type="text" size="30" id="email" name="email" class="reqd"></label></p>
<br>
<br>
<p><label for="reqUsername">Username: <input type="text" size="30" id="reqUsername" name="reqUsername" class="reqd"></label></p>
<p><label for="passOne">Password: <input type="password" size="30" id="passOne" name="passOne" class="reqd"></label></p>
<p><label for="passTwo">Confirm Password: <input type="password" size="30" id="passTwo" name="passTwo" class="reqd"></label></p>
<br>
<br>
<p><input type="submit" value="Submit"> <input type="reset" value="Reset Form" class="reset"></p>
</form>
</section>
<script type="text/javascript">
$("#registerBox").css("margin-left", ($(window).width()-425)/2);
$("#registerBox").css("margin-top", ($(document).height()-500)/2);
$('#registerBox').fadeIn(1500);
</script>
</body>
</html>
JS (regauth.js): Courtesy of Tom Negrino, Visual Quickstart Guide: Javascript Eighth Edition
window.onload = initForms;
//Function loops through each form. For each one it adds an event handler to that forms 'onSubmit'.
function initForms() {
for (var i = 0; i < document.forms.length; i++) {
document.forms[i].onsubmit = validForm;
}
}
function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");
for (var i = 0; i < allTags.length; i++) {
if (!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");
for (var j = 0; j < allClasses.length; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
if (outClass.indexOf("invalid") > -1) {
thisTag.focus();
if (thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;
function validBasedOnClass(thisClass) {
var classBack = "";
switch (thisClass) {
case "":
case "invalid":
break;
case "reqd":
if (allGood && thisTag.value == "") {
classBack = "invalid ";
}
classBack += thisClass;
break;
default:
classBack += thisClass;
}
return classBack;
}
}
}
Move the "invalid" CSS block to after the "reqd" one.
The rules for CSS are that the "last rule wins" (sort-of; it's more complicated but in this case that's the issue).
Even though the "invalid" rules apply to the invalid elements, because the "reqd" rule has a background color and because it comes after the "invalid" rule, that setting applies.