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.
Related
The idea is for the user to select the options and the best employment
sector would be suggested by the form based on his selection.
<!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>
Survey that will will give you suggestion.
</title>
<style>
/* Styling the Body element i.e. Color,
Font, Alignment */
body {
background-color: #05c46b;
font-family: Verdana;
text-align: center;
}
/* Styling the Form (Color, Padding, Shadow) */
form {
background-color: #fff;
max-width: 500px;
margin: 50px auto;
padding: 30px 20px;
box-shadow: 2px 5px 10px rgba(0, 0, 0, 0.5);
}
/* Styling form-control Class */
.form-control {
text-align: left;
margin-bottom: 25px;
}
/* Styling form-control Label */
.form-control label {
display: block;
margin-bottom: 10px;
}
/* Styling form-control input,
select, textarea */
.form-control input,
.form-control select,
.form-control textarea {
border: 1px solid #777;
border-radius: 2px;
font-family: inherit;
padding: 10px;
display: block;
width: 95%;
}
/* Styling form-control Radio
button and Checkbox */
.form-control input[type="radio"],
.form-control input[type="checkbox"] {
display: inline-block;
width: auto;
}
/* Styling Button */
button {
background-color: #05c46b;
border: 1px solid #777;
border-radius: 2px;
font-family: inherit;
font-size: 21px;
display: block;
width: 100%;
margin-top: 50px;
margin-bottom: 20px;
}
</style>
</head>
The form is made with HTML. and for javascript operations i have added
value=1 in the checkbox for generating the different output string.
please view the code below to understand better.
<body>
<h1>Your job type survey suggestion quiz</h1>
<!-- Create Form -->
<form id="form">
<!-- Details -->
<div class="form-control">
<label for="name" id="label-name">
Name
</label>
<!-- Input Type Text -->
<input type="text"
id="name"
placeholder="Enter your name" />
</div>
<div class="form-control">
<label for="email" id="label-email">
Email
</label>
<!-- Input Type Email-->
<input type="email"
id="email"
placeholder="Enter your email" />
</div>
<div class="form-control">
<label for="age" id="label-age">
Age
</label>
<!-- Input Type Text -->
<input type="text"
id="age"
placeholder="Enter your age" />
</div>
<div class="form-control">
<label for="role" id="label-role">
Which option best describes you?
</label>
<!-- Dropdown options -->
<select name="role" id="role">
<option value="student">Student</option>
<option value="intern">Intern</option>
<option value="professional">
Professional
</option>
<option value="other">Other</option>
</select>
</div>
<div class="form-control">
<label>
DO you like studying?
</label>
<!-- Input Type Radio Button -->
<label for="recommed-1">
<input type="radio"
id="recommed-1"
name="recommed">Yes</input>
</label>
<label for="recommed-2">
<input type="radio"
id="recommed-2"
name="recommed">No</input>
</label>
<label for="recommed-3">
<input type="radio"
id="recommed-3"
name="recommed">Maybe</input>
</label>
</div>
<div class="form-control">
<label>Skills that you have
<small>(Check all that apply)</small>
</label>
<!-- Input Type Checkbox -->
<label for="inp-1">
<input type="checkbox" name="inp" id="c" value=1>Coding</input></label>
<label for="inp-2">
<input type="checkbox" name="inp" id="d" value=2>Dancing</input></label>
</div>
<button onclick="checkCheckbox()">
Submit
</button>
</form>
Here as of now only 2 questions are in the form, I want to add more
questions and on based of the selection the form will suggest. In this
the alert or any message i`enter code here`s not shown neither there is any error.
<script>
function checkCheckbox() {
var c = document.getElementById("c");
var d = document.getElementById("d");
var add=0
if (c.checked == true){
var y = document.getElementById("c").value;
var add=y;
return add;
}
else if (d.checked == true){
var n = document.getElementById("d").value;
var add += n;
}
else {
return document.getElementById("error").innerHTML = "*Please mark any of checkbox";
}
if(add==2){
alert('You are multi-talented! become a dancer or a coder');
}
else{
alert('Become a coder');
</script>
</body>
</html>
here on selecting dancing and coding a different output should be
given and on selecting either dancing or either coding a different
output string should be shown. please suggest for any modifications or
if there is a better way to complete this idea.
There are several errors in the script section. You can use Web Developer debugging in your browser to check them out. I can see that you are new to coding in general, so there are a couple of common mistakes we've all made in the beginning.
This is one way of writing the function so it works as I think you intended it:
function checkCheckbox() {
var c = document.getElementById("c");
var d = document.getElementById("d");
var add = 0, val;
if (c.checked == true){
val = "coder";
add += 1;
}
if (d.checked == true){
val = "dancer";
add += 1;
}
if (add == 2) {
alert('You are multi-talented! become a dancer or a coder');
return true;
}
else if (add == 1) {
alert('Become a ' + val);
return true;
}
else {
document.getElementById("error").innerHTML = "*Please mark any of checkbox";
return false;
}
}
Also, you need to add return in the event handler of the button, to avoid it submitting when the form is invalid:
<button onclick="return checkCheckbox()">Submit</button>
And lastly add an element for the error message that is referred to in the script. Something like:
<div id="error"></div>
I'm trying to pass the first name and cars names to the other page, and I tried everything but doesn't work for me
once the user clicks on submit it's supposed to redirect to success.html page and show a message with their name and the cars they chose to test
this is page#1
h1 {
text-align: center;
color: #4A4A67;
font-weight: bold;
font-style: 'Amatic SC';
font-size: 55px; }
h3 {
font-size: 28px;
}
body { background-image: url("car.jpg");
text-align: center;
border-style: inset;
border-color: #8CA7B3;
font-family: 'Amatic SC';
font-weight: bold;
color: #6F6F9B;
border-radius: 25px;}
#fname:focus{
border-color: green;
background-color: lightgreen}
#Pnum:focus{
border-color: green;
background-color: lightgreen}
span {
color:darkred;
}
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Amatic SC' rel='stylesheet'>
<link rel="stylesheet" type="text/css" href="styles.css" media="screen">
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
document.getElementById("fname").style.borderColor = "red";
error1.textContent = "*Name must not be empty!"
return false;}
document.getElementById("fname").style.borderColor = "";
error1.textContent = ""
var y = document.forms["myForm"]["Pnum"].value;
if ( y == "" || isNaN(y) || (y.toString()).length>10 ){
document.getElementById("Pnum").style.borderColor = "red";
error2.textContent ="*Phone number invalid."
return false;}
document.getElementById("Pnum").style.borderColor = "";
error2.textContent = ""
var radios = document.getElementsByName("Age");
var formValid = false;
var i = 0;
while ( !formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++; }
if (!formValid){
error3.textContent = "Must check at least one option!"
return false;}
error3.textContent = ""
var checkbox = document.getElementsByName("cars");
var formValid = false;
var i = 0, x = 0;
while ( i < checkbox.length ) {
if (checkbox[i].checked) { x++; formValid = true; }
i++; }
if (!formValid) error4.textContent = "must check at least 1 option!"
if ( x > 3 ) { error4.textContent = "must check at most 3!"
return false; }
// Getting the value of your text input
var fname = document.getElementById("fname").value;
// Storing the value above into localStorage
localStorage.setItem("fname", fname);
return formValid;
}
</script>
</head>
<body>
<h1>Car Test Request</h1>
<h3>please fill in the form to make your car test request.</h3>
<form name="myForm" onsubmit="return validateForm()" action="file:///C:/Users/s/Desktop/457/assignment%202/success.html" method="GET">
<label for="FirstName">please enter your name:</label>
<input type="text" id="fname" name="fname" value=""><span id="error1"></span><br><br>
<label for="PhoneNumber">please enter your phone number:</label>
<input type="text" id="Pnum" name="Pnum" value=""><span id="error2"></span><br><br>
How old are you? <span id="error3"></span><br>
<input type="radio" name="Age" id="18-23">18-23<br>
<input type="radio" name="Age" id="23-30">23-30<br>
<input type="radio" name="Age" id="31-39">31-39<br>
<input type="radio" name="Age" id="40+">40+<br><br>
<h>choose the wanted car(s) for the test drive:</h> <span id="error4"></span><br>
<input type="checkbox" id="cars" name="cars" value="Bentley">
<label for="cars">Bentley</label>
<input type="checkbox" id="cars" name="cars" value="BMW">
<label for="cars">BMW</label>
<input type="checkbox" id="cars" name="cars" value="Cadillac">
<label for="cars">Cadillac</label><br>
<input type="checkbox" id="cars" name="cars" value="Dodge">
<label for="cars">Dodge</label>
<input type="checkbox" id="cars" name="cars" value="Fiat">
<label for="cars">Fiat</label>
<input type="checkbox" id="cars" name="cars" value="Ford">
<label for="cars">Ford</label><br>
<input type="checkbox" id="cars" name="cars" value="Jaguar">
<label for="cars">Jaguar</label>
<input type="checkbox" id="cars" name="cars" value="Mazda">
<label for="cars">Mazda</label><br><br><br><br><br><br><br><br>
<input type="submit">
<input type="reset">
<br><br>
</form>
</body> </html>
this is page#2 (success.html)
h1 {
text-align: center;
color: #4A4A67;
font-weight: bold;
font-style: 'Amatic SC';
font-size: 55px; }
h3 {
font-size: 28px;
}
body { background-image: url("car.jpg");
text-align: center;
border-style: inset;
border-color: #8CA7B3;
font-family: 'Amatic SC';
font-weight: bold;
color: #6F6F9B;
border-radius: 25px;}
#fname:focus{
border-color: green;
background-color: lightgreen}
#Pnum:focus{
border-color: green;
background-color: lightgreen}
span {
color:darkred;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css" media="screen">
<script>
// var fname = document.forms["myForm"]["fname"].value;
function init() {
// Retrieving the text input's value which was stored into localStorage
var fname = localStorage.getItem("fname");
}
</script>
</head>
<body>
<p>
<span id='fname'></span>, thanks for your request! <br>
we will call you soon to schedule a test drive for: <br>
</p>
<img src="bye.gif" alt="bye bye" width="200" height="200">
</body>
</html>
Instead of using method="GET" try using method="POST" and the proper URL inside the action=" second page URL " so that the data that you submit will be posted to the second page.Now use the localStorage.getItem() method on second page to get the data and show the data by using DOM like document.getElementId("").innerHTML = fname;
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" />
In the below code, after clicking on 'Save Data' I want the page to go to another htm page 'confrim.html'. Instead what is happening is its just showing "localhost:3000/confirm.html" and not opening a new page. Can anyone help to fix this, attaching the code for the reference.
I tried to implement the following through the submitInfo() function
Thanks
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">-->
<style>
* {
box-sizing:border-box;
border-color: teal;
}
html{
background : radial-gradient(rgba(48, 97, 97, 0.5),rgba(255,255,255,0.5))
}
div {
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: 'Times New Roman', Times, serif;
}
.input[type=button]{
font: 25px Calibri;
width: auto;
float: left;
cursor: pointer;
padding: 7px;
color: teal;
font-size: 30px;
}
#bt{
width : 190px;
height: 60px;
font-size: 25px;
font-family: 'Times New Roman', Times, serif;
background-color: #05193d;
color: whitesmoke;
box-shadow: 0 2px 2px 0 rgba(0,0,0,0.5);
margin-top: 10px;
}
input[type=text], textarea, select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color:teal
}
</style>
<title>Save form Data in a Text File using JavaScript</title>
<h1>User Information </h1>
<!--<link rel="stylesheet" href="style.css">-->
</head>
<body>
<div>
<form name="myForm" action="confirm.html" method="POST" >
<!--Add few elements to the form-->
<div>
<label for="Name">Name</label>
<input type="text" id="txtName" placeholder="Enter your name" required />
</div>
<div>
<label for="Email">Email</label>
<input type="text" id="txtEmail" placeholder="Enter your Email Id" />
</div>
<div>
<label for="Controller Type">Controller Type</label>
<select id="selProd">
<option value=""> - Select the Controller - </option>
<option value="RAID">RAID</option>
<option value="JBOD">JBOD</option>
<option value="EBOD">EBOD</option>
<option value="AP">AP</option>
</select>
</div>
<div>
<label for="Test Type">Test Type </label>
<select id="selTest">
<option value=""> - Select The Test - </option>
<option value="BFT">BFT</option>
<option value="Manufacturing">Manufacturing</option>
<option value="Channel">Channel</option>
<option value="DVT" >DVT</option>
</select>
</div>
<div>
<label for="Protocol Type">Protocol Type </label>
<select id="selProto">
<option value=""> - Select The Protocol - </option>
<option value="SAS">SAS</option>
<option value="iSCSI">iSCSI</option>
<option value="FC">FC</option>
</select>
</div>
<div>
<label for="IP Address">IP Address:</label>
<input type="text" id="txtIP" placeholder="Enter your IP address" />
</div>
<div>
<label for="Chasis Input">Number of Chasis Input:</label>
<input type="number" id="txtInputs" placeholder="Enter Number of Chasis" />
</div>
<div>
<input type="button" id="myBtn" value="Save data" onclick="submitInfo()"/>
</div>
<div>
<input type="button" id="bt" value="Save data to file" onclick="saveFile()" />
</div>
</form>
</div>
<script>
let saveFile = () => {
// Get the data from each element on the form.
const name = document.getElementById('txtName');
const email = document.getElementById('txtEmail');
const test = document.getElementById('selTest');
const product = document.getElementById('selProd');
const protocol = document.getElementById('selProto');
const IP = document.getElementById('txtIP');
const Inputs = document.getElementById('txtInputs');
// This variable stores all the data.
let data =
'\rName : ' + name.value + '\r\n' +
'Email ID : ' + email.value + '\r\n' +
'Test Type : ' + test.value + '\r\n' +
'Product Type : ' + product.value + '\r\n' +
'Protocol Type : ' + protocol.value + '\r\n' +
'IP Address : ' + IP.value + '\r\n' +
'Chasis Inputs : ' + Inputs.value;
if(name.value =='' || email.value == '' || test.value =='' || product.value =='' || IP.value == ''|| Inputs.value == ''){
alert("Please fill all the fields!");
return;
}
const reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == false)
{
alert('Invalid Email Address');
return false;
}
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(IP.value) == false)
{
alert('Invalid IP Address');
return false;
}
if(name.value.length<3){
alert("Name must be having atleast 3 Characters");
return;
}
if(name.value == ''){
alert("Enter the name First");
}
// Convert the text to BLOB.
const textToBLOB = new Blob([data], { type: 'text/plain' });
const sFileName = 'formData.yaml'; // The file to save the data.
let newLink = document.createElement("a");
newLink.download = sFileName;
if (window.webkitURL != null) {
newLink.href = window.webkitURL.createObjectURL(textToBLOB);
}
else {
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
}
newLink.click();
}
var disable_options = false;
document.getElementById('selProd').onchange = function () {
//alert("selected value = "+this.value);
if(this.value == "RAID")
{
document.getElementById('selProto').removeAttribute('disabled');
}
else
{
document.getElementById('selProto').setAttribute('disabled', true);
}
}
function submitInfo(){
var test = document.getElementById('selTest').value;
var product = document.getElementById('selProd').value;
if(product == "EBOD" && test== "BFT"){
window.location ="confirm.html";
}
}
</script>
</body>
</html>
You could use the window.open method - like so:
function submitInfo(){
var test = document.getElementById('selTest').value;
var product = document.getElementById('selProd').value;
if( product == "EBOD" && test== "BFT" ){
window.open( "confirm.html", "Confirm", "fullscreen=yes,location=no,menubar=yes,resizable=no,scrollbars=no,status=no,toolbar=no" );
}
}
you have a
<form name="myForm" action="confirm.html" method="POST" >
which, on form submit, your browser will look for confirm.html file. I don't know whether you have file named confirm.html, but I think you do. otherwise it'll show 404 error.
As you instructed in your form, browser'll look for confirm.html, and on redirect, it'll show what's in confirm.html file.
you should remove your js script from this file and put it inside confirm.html file. or just replace action="confirm.html" with action=""
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>