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>
Related
This is with regard to an ongoing question asked previously. I am trying to make a contact form to work using HTML, CSS and JavaScript. All my conditions seem to be working fine. The issue here is that whenever I fail to enter a particular field, and later re-enter it, the error message is still being displayed. Also, I want the user to be redirected to another HTML page once he clicks on Submit and once all conditions are satisfied. I would like some guidance on the same. Herewith attaching the code for reference.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register with us</title>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/styles.css">
</head>
<body style="position: relative;">
<div class="container"> <br>
<h1 class="text-center">Register with Us!</h1>
<form>
<div class="form-group">
<label for="fname" id="firstname">First name: </label>
<input type="text" class="form-control" id="fname" placeholder="Enter your first name">
<small id="firstnameerror" class="form-text"></small>
</div>
<div class="form-group">
<label for="lname" id="lastname">Last name: </label>
<input type="text" class="form-control" id="lname" placeholder="Enter your last name">
<small id="lastnameerror" class="form-text"></small>
</div>
<div class="form-group">
<label for="emailid" id="emailaddress">Email address:</label>
<input type="email" class="form-control" id="emailid" aria-describedby="emailHelp"
placeholder="Enter email">
<small id="emailerror" class="form-text"></small>
</div>
<div class="form-group">
<label for="pass1" id="password1">Password: </label>
<input type="password" class="form-control" id="pass1" placeholder="Enter a password">
<small id="passerror" class="form-text"></small>
</div>
<div class="form-group">
<label for="confirmpass" id="password2">Confirm Password: </label>
<input type="password" class="form-control" id="confirmpass" placeholder="Re-enter password">
<small id="passerror2" class="form-text"></small>
</div>
<div class="form-group">
<label for="phno" id="ctno">Contact number : </label>
<input type="number" class="form-control" id="phno" placeholder="Enter your number here">
<small id="phoneerror" class="form-text"></small>
</div>
<button type="submit">Submit</button>
</form>
</div>
<script src="/js/vaildate.js"></script>
</body>
</html>
#firstnameerror,
#lastnameerror,
#emailerror,
#passerror,
#phoneerror{
color: tomato;
font-size: 1.1em;
margin-left: 10%;
margin-top: 2.5%;
}
#firstname,#lastname,#emailaddress,#password1,#password2,#ctno{
padding: 0.7em;
font-size: 1.3em;
font-family: 'Noto Sans', sans-serif;
font-weight: 600;
text-align: center;
color: white;
margin-left: 9%;
}
#fname,#lname,#emailid,#pass1,#confirmpass,#phno{
margin: 0.3em 0.7em;
width: 80%;
font-family: 'Poppins', sans-serif;
margin-left: 10%;
background-color: black;
border: none;
padding: 1em;
border-radius: 2em;
color: white;
}
.container{
margin-top: 20vh;
background-image: linear-gradient(to right, rgb(46, 46, 46) , rgb(20, 20, 20));
border-radius: 5em;
}
.container h1{
color: white;
}
button{
margin-left: 10%;
margin-top: 2.5%;
font-size: 1.4em;
padding: 0.5em 1em;
font-family: 'Open Sans', sans-serif;
border-radius: 1.2em;
outline: none;
border: none;
background-color: teal;
color: white;
font-weight: bold;
}
const form = document.querySelector(".container");
const firstname = document.getElementById("fname");
const lastname = document.getElementById("lname");
const emailid = document.getElementById("emailid");
const password = document.getElementById("pass1");
const confirmpassword = document.getElementById("confirmpass");
const phoneno = document.getElementById("phno");
// Function to check if first name is entered properly
function checkfname(fname) {
let letters = /^[A-Z]+[a-z]+$/;
if (fname.match(letters)) {
document.getElementById("firstnameerror").innerHTML.style = "none";
return fname;
}
else {
document.getElementById("firstnameerror").innerHTML = "Please enter the details accurately";
return false;
}
}
// Function to check if first name is entered properly
function checklname(lname) {
let letter = /^[A-Z]+[a-z]+$/;
if (lname.match(letter)) {
document.getElementById("firstnameerror").innerHTML.style = "none";
return lname;
}
else {
document.getElementById("firstnameerror").innerHTML = "Please enter the details accurately";
return false;
}
}
//function to check if the password is entered properly
function passcheck(pass) {
var paswd = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{7,15}$/;
if (pass.match(paswd)) {
document.getElementById("passerror").innerHTML.style = "none";
return pass;
}
else {
document.getElementById("passerror").innerHTML = "Entered password does not meet the requirements";
return false;
}
}
function phonecheck(phval) {
var phonecheck = /\+?\d[\d -]{8,12}\d/;
if (phval.match(phonecheck)) {
document.getElementById("phoneerror").innerHTML.style = "none";
return phval;
}
else {
document.getElementById("phoneerror").innerHTML = "Please enter a valid phone number";
return false;
}
}
// Function to check if all parameters have been entered
function testfunc() {
if (firstname.value == "") {
document.getElementById("firstnameerror").innerHTML = "Please enter your first name";
}
else {
firstname.value = checkfname(firstname.value);
}
if (lastname.value == "") {
document.getElementById("lastnameerror").innerHTML = "Please enter your last name";
}
else {
lastname.value=checklname(lastname.value);
}
if (emailid.value == "") {
document.getElementById("emailerror").innerHTML = "Please enter your E-mail ID";
}
else {
document.getElementById("emailerror").innerHTML.style = "none";
}
if (password.value == "") {
document.getElementById("passerror").innerHTML = "Please enter a password";
}
else {
password.value=passcheck(password.value);
}
if (confirmpassword.value == "") {
document.getElementById("passerror2").innerHTML = "Enter the password again"
}
else if (confirmpassword.value == password.value) {
document.getElementById("passerror2").innerHTML.style = "none";
document.getElementById("passerror").innerHTML.style = "none";
}
else {
document.getElementById("passerror2").innerHTML = "Passwords do not match";
}
if (phoneno.value == "") {
document.getElementById("phoneerror").innerHTML = "Please enter your mobile number";
}
else {
phoneno.value = phonecheck(phoneno.value);
}
}
form.addEventListener("submit", function (e) {
e.preventDefault();
testfunc();
}
)
If I were you, I would add event listeners (on change) for each of the inputs. Then save the value of those inputs to variables and clear the error message of that particular input. This way makes the most sense to me from a user experience perspective.
As for the submit function's redirect, just use one of the ways W3Schools suggests:
// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";
// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com")
Also,
document.getElementById("firstnameerror").innerHTML.style = "none";
wont work. What you're looking for is probably either clearing the text:
document.getElementById("firstnameerror").innerHTML = "";
Or hiding the element itself:
document.getElementById("firstnameerror").style.display = "none";
.style = "none" won't work.
.style.display = "none" is probably what you want.
Also, you can probably do everything (or nearly everything) of what you're checking in Javascript via HTML form validation as well, e.g. required attribute.
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'))
}
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.
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;
}
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.