Form and input validation - javascript

I am trying to get two inputs inside of a form tag to bring up a error message if you leave either of them blank.
I went to w3schools and tried their code but it does not work. (see below)
HTML
<form name="myForm" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Js
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
I removed the action="demo_form.asp" from the code because my teacher told me to
Here is my code
HTML
<div class="loginShite">
<form name="username" onsubmit="return validateForm()" method="post">
<input type="text" name="username" placeholder="#Username" />
<input type="password" name="password" placeholder="Password" />
<br />
</form>
<div class="loginButton">
<a href="#homePage">
<input type ="button" value="login" />
</a>
</div>
</div>
Js
function validateForm() {
var x = document.forms["username"]["password"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
I would be greatly appreciative is somebody could either tell me what I'm doing wrong OR point me in the right direction to solve the problem.
Thank you in advance.

use type="submit" instead use of type="button",it works fine
<head>
<script>
function validateForm() {
var x = document.forms["username"]["password"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<div class="loginShite">
<form name="username" onsubmit="return validateForm()" method="post">
<input type="text" name="username" placeholder="#Username" />
<input type="password" name="password" placeholder="Password" /> <br
/>
<div class="loginButton"><a href="#homePage">
<input type ="submit" value="login" /></a></div> </a></div>
</form>
</div>
</body>

<!DOCTYPE html>
<html>
<head>
<script>
function validate(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validateForm(){
var fname = document.getElementById("fname").value;
if(fname == ""){
alert("Please Enter first name");
return false;
}
var lname = document.getElementById("lname").value;
if(lname == ""){
alert("Please Enter last name");
return false;
}
var mnumber = document.getElementById("mnumber").value;
if(mnumber == ""){
alert("Please Enter Mobile no");
return false;
}
if((mnumber.length <10)){
alert("Please Enter 10 DIGIT mobile no");
return false;
}
if((mnumber.length >10)){
alert("Please Enter 10 DIGIT mobile no");
return false;
}
var message = document.getElementById("message").value;
if(message == ""){
alert("Please Enter Message");
return false;
}
}
</script>
</head>
<body>
<form onsubmit="return validateForm()" name="form" id="form" action="" method="post">
<input type="text" name="fname" id="fname" placeholder="fname" />
<br />
<input type="text" name="fname" id="lname" placeholder="lname" />
<br />
<input type="text" name="mnumber" id="mnumber" placeholder="mnumber" onkeypress="validate(event)" />
<br />
<input type="text" name="message" id="message" placeholder="message" />
<br />
<input type="submit" value="Submit">
</form>
</html>
</body>

Here's how i've done it. You need to make sure the input type for button is "submit" else the form will not consider it as a trigger to submit. then you need to use || conditionals to test both the field conditions if they are blank or not. You can secure it more by adding the trim() method to avoid any accidental whitespaces getting accepted
Here's the HTML
<form onsubmit="return validate()" action="" class="form-group">
<div style="margin-top:2%">
<div class="col-md-4"> // bootstrap
<input type="text" id="uname" placeholder="user name"><br>
<input type="password" id="pass" placeholder="password"><br>
<input type="submit" class="btn btn-primary"><br><br>
<p id="demouname"></p>
<p id="succesuname"></p>
</div>
</div>
and here's the JS
function validate() {
var username = document.getElementById("uname");
var password = document.getElementById("pass");
if (username.value.trim() == "" || password.value.trim() == "") {
document.getElementById("demouname").style.display = "block";
document.getElementById("demouname").innerHTML = "No Empty Values Allowed";
return false;
} else {
document.getElementById("succesuname").style.display = "block";
document.getElementById("succesuname").innerHTML = "Success";
true;
}
}
and some basic css for added styling
#demouname {
display: none;
padding: 10px;
border: solid red 1px;
background-color: rgba(250, 232, 232, 0.2);
color: red;
border-radius: 5px;
-webkit-animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}
#succesuname {
display: none;
padding: 10px;
border: solid green 1px;
background-color: rgba(251, 252, 251, 0.521);
color: green;
border-radius: 5px;
-webkit-animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
animation: shadow-drop-2-center 0.4s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}
}
#-webkit-keyframes shadow-drop-2-center {
0% {
-webkit-transform: translateZ(0);
transform: translateZ(0);
box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
}
100% {
-webkit-transform: translateZ(50px);
transform: translateZ(50px);
box-shadow: 0 0 20px 0px rgba(255, 255, 255, 0.35);
}
}
#keyframes shadow-drop-2-center {
0% {
-webkit-transform: translateZ(0);
transform: translateZ(0);
box-shadow: 0 0 0 0 rgba(0, 0, 0, 0);
}
100% {
-webkit-transform: translateZ(50px);
transform: translateZ(50px);
box-shadow: 0 0 20px 0px rgba(0, 0, 0, 0.35);
}
}

Your button type should be "submit" and should be inside </form> tag.
See the form tag name and see the JavaScript how to get values from form tag.
Update
<!doctype html>
<html>
<script type="text/javascript">
function validateForm() {
var x = document.yourFormName.username.value;
var y = document.yourFormName.password.value;
if (x == "" || y == "" )
{
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="yourFormName" onsubmit="return validateForm(this.form)" method="post">
<input type="text" name="username" placeholder="#Username" />
<input type="password" name="password" placeholder="Password" />
<input type ="submit" value="login" />
</form>
</body>
</html>

Actually, all you have to do is put required at the end of the first input tag. For example:
<form>
<input type=“text” required>some text</input>
<!—-some other input—->
<input type=button>submit</input>
</form>
I believe that should work.

Related

Remove previously set border color

function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "") {
document.getElementById("message").innerHTML = "USERNAME CANNOT BE EMPTY";
document.getElementById("username").style.borderColor = "red";
return false;
}
if (password == "") {
document.getElementById("message").innerHTML = "PASSWORD CANNOT BE EMPTY";
document.getElementById("password").style.borderColor = "red";
return false;
}
}
#username:focus {
background-color: yellow;
border-color: green;
}
#password:focus {
background-color: yellow;
border-color: green;
}
#message {
color: red;
}
<form onsubmit=" return validate()">
LOGIN:-
<br>
<input id="username" type="text" name="username" placeholder="USERNAME">
<br>
<input id="password" type="password" name="password" placeholder="PASSWORD">
<br>
<input type="submit" value="SUBMIT">
<p id="message">
</form>
When i focus on the text fields, the background and border color changes to yellow and green respectively (through css).
If i click on submit without entering anything, the border color changes to red (through javascript).
But when i bring the focus on the text field again, the red border color does not go away, instead i get both green and red borders.
I want it to be green only. Can you also explain the reason for this behavior.
This is happening because you have updated the element style instead of CSS class property. Element style has the highest weight for CSS. Instead add an error class dynamically on error and remove it when the form field is valid.
As per the documentation, the order of style in decreasing order will be.
Inline style (inside an HTML element)
External and internal style sheets (in the head section)
Browser default
Here is a working example
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "") {
document.getElementById("message").innerHTML = "USERNAME CANNOT BE EMPTY";
document.getElementById("username").classList.add("invalidInput");
return false;
} else {
document.getElementById("username").classList.remove("invalidInput")
}
if (password == "") {
document.getElementById("message").innerHTML = "PASSWORD CANNOT BE EMPTY";
document.getElementById("password").classList.add("invalidInput")
return false;
} else {
document.getElementById("password").classList.remove("invalidInput")
}
}
#username:focus {
background-color: yellow;
border-color: green;
}
#password:focus {
background-color: yellow;
border-color: green;
}
.invalidInput {
border-color: red;
}
#message {
color: red;
}
<form onsubmit=" return validate()">
LOGIN:-
<br />
<input id="username" type="text" name="username" placeholder="USERNAME" />
<br />
<input id="password" type="password" name="password" placeholder="PASSWORD" />
<br />
<input type="submit" value="SUBMIT" />
<p id="message"></p>
</form>
The problem is the colors have the same level of importance to css and therefore the code does not know which one to prioritize. So, to fix that, you have to make the green more important in the css code.
To do that change the focus css code to look like this.
#username:focus {
background-color: yellow !important;
border-color: green !important;
}
#password:focus {
background-color: yellow !important;
border-color: green !important;
}
#message {
color: red;
}
Hope this helps!
Instead adding color from javascript you can use required in input box and :invalid in CSS. Check the snippet
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "") {
document.getElementById("message").innerHTML = "USERNAME CANNOT BE EMPTY";
//document.getElementById("username").style.borderColor = "red";
return false;
}
if (password == "") {
document.getElementById("message").innerHTML = "PASSWORD CANNOT BE EMPTY";
//document.getElementById("password").style.borderColor = "red";
return false;
}
}
#username:focus{
background-color: yellow;
border-color: green;
}
#username:invalid{
background-color: none;
border-color: red;
}
#password:focus{
background-color: yellow;
border-color: green;
}
#password:invalid{
background-color: none;
border-color: red;
}
#message {
color: red;
}
<form onsubmit=" return validate()">
LOGIN:-
<br>
<input id="username" type="text" name="username" placeholder="USERNAME" required>
<br>
<input id="password" type="password" name="password" placeholder="PASSWORD" required>
<br>
<input type="submit" value="SUBMIT">
<p id="message">
</form>
You can simply revert the border color on keyup and create a new class error to overwrite border color to red
function retainColor(ele){
ele.style.borderColor = "inherit";
document.getElementById("message").innerHTML = "";
}
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "") {
document.getElementById("message").innerHTML = "USERNAME CANNOT BE EMPTY";
document.getElementById("username").classList.add("error");
return false;
}else{
document.getElementById("username").classList.remove("error");
}
if (password == "") {
document.getElementById("message").innerHTML = "PASSWORD CANNOT BE EMPTY";
document.getElementById("password").classList.add("error");
return false;
}else{
document.getElementById("password").classList.remove("error");
}
}
#username:focus {
background-color: yellow;
border-color: green;
}
#password:focus {
background-color: yellow;
border-color: green;
}
.error {
border-color: red;
}
.error {
border-color: red;
}
#message {
color: red;
}
<form onsubmit=" return validate()">
LOGIN:-
<br>
<input id="username" type="text" onkeyup="retainColor(this)" name="username" placeholder="USERNAME">
<br>
<input id="password" type="password" onkeyup="retainColor(this)" name="password" placeholder="PASSWORD">
<br>
<input type="submit" value="SUBMIT">
<p id="message">
</form>
You're setting the colors via JS, but never un-setting them, so essentially they're being set permanently.
One way to stop this behavior is to also add another function that catches the OnClick event of the text fields, and "reset" or unset the colors when they're get clicked inside of.
Have a look here for an idea on how to get started handling the OnClick event:
https://jsfiddle.net/warunamanjula/qy0hvmyq/1/
Because when you add color from javascript, or any property of css, it's added inline, so just write focus border-color !important.
Just add onfocus attribute
Javascript
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == "") {
document.getElementById("message").innerHTML = "USERNAME CANNOT BE EMPTY";
document.getElementById("username").style.borderColor = "red";
return false;
}
if (password == "") {
document.getElementById("message").innerHTML = "PASSWORD CANNOT BE EMPTY";
document.getElementById("password").style.borderColor = "red";
return false;
}
}
function myfunction(var id){
document.getElementById(id).style.borderColor = "green";
document.getElementById(id).style.background-color= "yellow";
}
Html
<form onsubmit=" return validate()">
LOGIN:-
<br>
<input id="username" type="text" onfocus="myFunction('username')" name="username" placeholder="USERNAME">
<br>
<input id="password" type="password" onfocus="myFunction('password')" name="password" placeholder="PASSWORD">
<br>
<input type="submit" value="SUBMIT">
<p id="message">
</form>

Multiple forms relating to Javascript in one WEB-page

I want to have two forms on the same page, one for userregistration, and one for editing a comanys name. This is how I have gotten so far...
test001.js:
$(document).ready(function() {
$(function() {
$("#dialog").dialog({
autoOpen: false
});
$("#button").on("click", function() {
$("#dialog").dialog("open");
});
});
// Validating Form Fields.....
$("#submit").click(function(e) {
var email = $("#email").val();
var comnpanyname = $("#companyname").val();
var lastname = $("#lastname").val();
var password = $("#password").val();
var emailReg = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (firstname === '' || lastname === '' || password === '' || email === '') {
alert("Please fill all fields!");
e.preventDefault();
} else if (!(email).match(emailReg)) {
alert("Invalid Email!");
e.preventDefault();
} else {
alert("Form Submitted Successfully.");
}
});
});
test001.css
#import "http://fonts.googleapis.com/css?family=Droid+Serif";
/* Above line is used for online google font */
h2 {
text-align:center;
font-size:24px
}
hr {
margin-bottom:30px
}
p {
color:#000;
font-size:16px;
font-weight:700
}
#button,#button2 {
border:1px solid #0c799e;
width:250px;
padding:10px;
font-size:16px;
font-weight:700;
color:#fff;
border-radius:3px;
background:linear-gradient(to bottom,#59d0f8 5%,#49c0e8 100%);
cursor:pointer
}
#button:hover,#button2:hover {
background:linear-gradient(to bottom,#49c0e8 5%,#59d0f8 100%)
}
input[type=text] {
margin-top:5px;
margin-bottom:20px;
width:96%;
border-radius:5px;
border:0;
padding:5px 0
}
#firstname,#lastname,#email,#password,#company {
padding-left:10px
}
input[type=submit] {
width:30%;
border:1px solid #59b4d4;
background:#0078a3;
color:#eee;
padding:3px 0;
border-radius:5px;
margin-left:33%;
cursor:pointer
}
input[type=submit]:hover {
border:1px solid #666;
background:#555;
color:#fff
}
.ui-dialog .ui-dialog-content {
padding:2em
}
/* 960x610 */
div.container {
width:500px;
height:300px;
margin:50px auto;
font-family:'Droid Serif',serif;
position:relative
}
div.container2 {
width:960px;
height:610px;
margin:50px auto;
font-family:'Droid Serif',serif;
position:relative
}
div.main {
width:320px;
margin-top:35px;
float:left;
padding:10px 55px 25px;
background-color:rgba(204,204,191,0.51);
border:15px solid #fff;
box-shadow:0 0 10px;
border-radius:2px;
font-size:13px;
text-align:center
}
div.main2 {
width:320px;
margin-top:35px;
float:left;
padding:10px 55px 25px;
background-color:rgba(204,204,191,0.51);
border:15px solid #fff;
box-shadow:0 0 10px;
border-radius:2px;
font-size:13px;
text-align:center
}
<!DOCTYPE html>
<html>
<head>
<title>jQuery Dialog Form Example</title>
<link href="http://enersen.no/development/eds/css/test001.css" rel="stylesheet">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/ui-darkness/jquery-ui.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script src="http://enersen.no/development/eds/js/user.js" type="text/javascript"></script>
<!-- script src="http://enersen.no/development/eds/js/company.js" type="text/javascript"></script -->
</head>
<body>
<div class="container">
<div class="main">
<div id="dialog" title="Dialog Form">
<form action="" method="post">
<label>First name:</label>
<input id="firstname" name="firstname" type="text">
<label>Last name:</label>
<input id="lastname" name="lastname" type="text">
<label>Email:</label>
<input id="email" name="email" type="text">
<label>Password:</label>
<input id="password" name="password" type="password">
<input id="submit" type="submit" value="Submit">
</form>
</div>
<h2>jQuery Dialog Form Example</h2>
<p>Click below button to see jQuery dialog form.</p>
<input id="button" type="button" value="Open Dialog Form">
</div>
</div>
<div class="container2">
<div class="main2">
<div id="dialog2" title="Dialog Form 2">
<form action="" method="post">
<label>New comany name:</label>
<input id="company" name="company" type="text">
<input id="submit" type="submit" value="Submit">
</form>
</div>
<h2>jQuery Dialog Form Example</h2>
<p>Click below button to see jQuery dialog form.</p>
<input id="button2" type="button" value="Open Company Dialog Form">
</div>
</div>
</body>
</html>
I expect the form that I activate to be the one evaluated. Now it is the form for adress-/login-info that gets evaluated. I guess I need some code snipplet that lets med deal with the forms as different documents in Javascript?
You have more than one submit button with the id submit - simply change them to be unique - where you use an id attribute, they should always be unique for the page.
For example, use userRegistrationSubmit for one and then change this:
$("#submit").click(function(e) {
to
$("#userRegistrationSubmit").click(function(e) {
You could call the other companyNameChangeSubmit.
Thanks, Jamiec, you pointed me in the rigth direction and I solved it :-) Here's the result:
$(document).ready(function() {
$(function() {
$("#userDialog").dialog({
autoOpen: false
});
$("#companyDialog").dialog({
autoOpen: false
});
$("#userButton").on("click", function() {
$("#userDialog").dialog("open");
});
$("#companyButton").on("click", function() {
$("#companyDialog").dialog("open");
});
});
// Validating Form Fields.....
$("#userSubmit").click(function(e) {
var email = $("#email").val();
var comnpanyname = $("#companyname").val();
var lastname = $("#lastname").val();
var password = $("#password").val();
var emailReg = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (firstname === '' || lastname === '' || password === '' || email === '') {
alert("Please fill all fields!");
e.preventDefault();
} else if (!(email).match(emailReg)) {
alert("Invalid Email!");
e.preventDefault();
} else {
alert("Form Submitted Successfully.");
}
});
});

Form Field Submission

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.

A toggle between 2 elements in pure JavaScript

I am writing a toggle in pure JavaScript.
There are 2 input fields, 1 is hidden and the other is visible. When we click on the first 1, the second input should appear and when both of the input fields are visible and one of the input fields is clicked then that input field should display:block and the other input field should display:none. Also, the latest clicked input element should remain on top and the other one below it. (es6 would be also good)
if anyone knows please check ?
code
<form action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww" placeholder="Type "></form>
<form action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww1" placeholder="Type "></form>
body{
background:#873e66;
}
.input-bg{
background:white;
border:none;
color:black;
height:50px;
text-indent:15px;
width:500px;
border-radius:26px;
outline:none;
}
.neww1{
margin-top:5px;
}
::-webkit-input-placeholder {
color: black;
}
::-moz-placeholder {
color: black;
}
:-ms-input-placeholder {
color: black;
}
.neww1{
display:none;
}
function toggleClass(element, className){
if (!element || !className){
return;
}
var classString = element.className, nameIndex = classString.indexOf(className);
if (nameIndex == -1) {
classString += ' ' + className;
}
else {
classString = classString.substr(0, nameIndex) + classString.substr(nameIndex+className.length);
}
element.className = classString;
}
Thanks!
you can proceed like :
const inputs = [].slice.call(document.getElementsByClassName("input-bg"));
inputs.forEach((input) => {
console.log()
input.addEventListener("click", (event) => {
const somehidden = inputs.filter((_input) => {
return _input.getAttribute("class").match(/neww1/i);
})
if (somehidden.length > 0) {
somehidden[0].classList.remove("neww1");
} else {
inputs.forEach((i) => {
if (i !== event.target)
i.classList.add("neww1");
});
}
});
});
body {
background: #873e66;
}
.grid {
display: grid;
grid-template-areas: "up" "down";
}
form:focus-within {
grid-area: up;
}
.input-bg {
background: white;
border: none;
color: black;
height: 50px;
text-indent: 15px;
width: 500px;
border-radius: 26px;
outline: none;
}
.neww1 {
margin-top: 5px;
}
::-webkit-input-placeholder {
color: black;
}
::-moz-placeholder {
color: black;
}
:-ms-input-placeholder {
color: black;
}
.neww1 {
display: none;
}
<div class="grid">
<form action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww" placeholder="Type "></form>
<form action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww1" placeholder="Type2 "></form>
</div>
Although your requirement is not very clear but my answer might be of some help
Let's say we have two input fields like this:
<div class="input-container">
<input type="password" placeholder="Input 1" class="myInput first" />
<input type="password" placeholder="Input 2" class="myInput second hidden" />
</div>
CSS can be like:
.input-container {
display: flex;
flex-direction: column;
}
.myInput {
margin: 10px;
padding: 5px
}
.first {
order: 1;
}
.second {
order: 2;
}
.hidden {
display: none;
}
Now the toggle function (JS):
var allInputs = document.querySelectorAll('.myInput');
allInputs.forEach(function(node) {
node.addEventListener("click", function(){
var allHiddenInputs = document.querySelectorAll('.hidden');
if(allHiddenInputs.length === 0) {
allInputs.forEach(function(input) {
input.classList.add("hidden");
input.classList.add("second");
input.classList.remove("first");
});
node.classList.remove("hidden");
node.classList.remove("second");
node.classList.add("first");
} else {
allHiddenInputs.forEach(function(input) {
input.classList.remove("hidden");
});
}
});
});
https://codepen.io/tusharshukla/pen/rrqvQz?editors=1010
Something like this could help you. I'm directly changing the CSS but you can also toggle classes using the classList.
<html>
<body>
<form action="#" class="navbar-top" role="search" autocomplete="off">
<input name="p" id="input1" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww"
placeholder="Input One ">
</form>
<form action="#" class="navbar-top" role="search" autocomplete="off">
<input name="p" id="input2" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww1"
placeholder="Input Two ">
</form>
<script>
(function () {
const inputOne = document.getElementById('input1');
const inputTwo = document.getElementById('input2');
const handleClick = i => (i === inputOne ? inputTwo : inputOne)
.style.display = 'none';
const handleBlur = i => {
if (i === inputOne) {
inputTwo.style.display = 'block';
inputOne.style.display = 'none';
} else {
inputTwo.style.display = 'none';
inputOne.style.display = 'block';
}
}
[inputOne, inputTwo].forEach((i) => {
i.addEventListener('click', () => handleClick(i))
i.addEventListener('focusout', () => handleBlur(i))
});
})();
</script>
</body>
</html>
You have the classList attribute with your HTML Element.
So first you need the element reference, you can use your constructor and private variables and set the private variable with document.getElementByClassName according to initial state of your page, or set an ID. Let's take for example an ID :
<form onclick="toggleClass()" id="password1" action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww" placeholder="Type "></form>
<form onclick="toggleClass()" id="password2" action="#" class="navbar-top" role="search" autocomplete="off"><input name="p" data-hit="Type" type="text" autocomplete="new-password" value="" data-open="false" class="input-bg neww1" placeholder="Type "></form>
Then just find the reference
const password1 = document.getElementById("password1");
const password2 = document.getElementById("password2");
and after that, you can write this function :
function toggleClass() {
const password1 = document.getElementById("password1");
const password2 = document.getElementById("password2");
if (password1.classList.contains('hidden')){
password1.classList.remove('hidden');
password2.classList.add('hidden');
}
else {
password2.classList.remove('hidden');
password1.classList.add('hidden');
}
}
.neww1 {
background-color : red;
}
.neww {
background-color : green;
}
.hidden {
display:none;
}
input {
margin:5px;
}

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/

Categories