I have two radio buttons, (Yes and No) when the user choses Yes, a set of text boxes will appear and is required to have at least one entry in order to submit. If the user chose "No" he/she can submit with no entries or whatsoever. I have everything working except for the "No" part.
The validation function works inside the form, is there anyway to disable it when the chosen button is "No"?
<script type="text/javascript">
function checkEvent() {
console.log("infunc");
if(document.getElementById('events_yes').checked){
document.getElementById('if_events_yes').style.display = "block";
}
else{
document.getElementById('if_events_yes').style.display = "none";
document.getElementById('myForm').removeAttribute("onsubmit","");
}
}
</script>
<form action="ResponseDB" method="post" id="myForm">
<input name="tipid" value="<% out.println(tipid);%>" type = "hidden">
Any events to report?<br>
<input type="radio" name="events" onclick="checkEvent()" id="events_yes" value="no">Yes<br>
<input type="radio" name="events" onclick="checkEvent()" id="events_no" value="yes" checked>No<br>
<div id="if_events_yes" style="display:none">
<br><br>
Firewall:<br>
<textarea rows="5" cols="80" name="firewall"></textarea><br>
IDS/IPS:<br>
<textarea rows="5" cols="80" name="ids"></textarea><br>
Web Content Filtering/Proxy:<br>
<textarea rows="5" cols="80" name="proxy"></textarea><br>
Deep packet inspection:<br>
<textarea rows="5" cols="80" name="dpi"></textarea><br>
Network malware protection devices (FireEye, Damballa, etc.):<br>
<textarea rows="5" cols="80" name="net_malware"></textarea><br>
Anti-virus software:<br>
<textarea rows="5" cols="80" name="av" id="av"></textarea><br>
Forensics Tools:<br>
<textarea rows="5" cols="80" name="forensics"></textarea><br>
Tripwire:<br>
<textarea rows="5" cols="80" name="tripwire"></textarea><br>
Memory Dumps:<br>
<textarea rows="5" cols="80" name="memdumps"></textarea><br>
Email logs:<br>
<textarea rows="5" cols="80" name="email_logs"></textarea><br>
</div>
<input type="submit" value="Submit">
</form>
<script>
onsubmit=function() {
var t = document.getElementsByTagName("textarea"),
l = 0;
for(var i = 0; i < t.length; i++){
l = l + t[i].value.trim();
}
if (l < 1) {
alert("Please have at least one entry");
return false;
}
}
</script>
This is the portion I'm working on. Is there anyway I can disable the onsubmit function when the user choses No?
You should be able to use this example from w3schools. Their example sends to an asp page, but that doesn't matter.
I have copied the part you need here, but for more details on how or why it works visit the link above.
JavaScript Part
a JavaScript function like this but checking the state of your radio buttons:
function validateForm() {
//here just get the value(s) from your radio(s)
var x = document.forms["myForm"]["fname"].value;
//check the value
if (x == null || x == "") {
alert("Name must be filled out");
//this prevents the submit to your server
return false;
}
}
Form Part
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
It is working thanks to Kevin2 from webdeveloper.com forums....
<%#page import="com.sun.xml.internal.txw2.Document"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="db.ResponseTracker"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MASC Response Form</title>
<style>
/* this selector could be div#nav instead of nav depending on which tag you wrapped the ul in */
#nav {
width: 100%;
float: left;
margin: 0 0 1em 0;
padding: 0;
background-color: #f2f2f2;
border-bottom: 1px solid #ccc; }
#nav ul {
list-style: none;
width: 800px;
margin: 0 auto;
padding: 0; }
#nav li {
float: left; }
#nav li a {
display: block;
padding: 8px 15px;
text-decoration: none;
font-weight: bold;
color: #069;
border-right: 1px solid #ccc; }
#nav li:first-child a {
border-left: 1px solid #ccc; }
#nav li a:hover {
color: #c00;
background-color: #fff; }
#tipid, fieldset {
display: none;
}
label {
display: block;
}
fieldset {
border: 0;
width: 50%;
}
textarea {
width: 100%;
height: 5em;
}
.active {
position: fixed;
left: 54%;
bottom: 2em;
}
</style>
<script src="nav.jsp"></script>
</head>
<body>
<div id="nav">
<ul>
<li>My Data</li>
<li>Logout</li>
</ul>
</div>
<% ResponseTracker tracker = new ResponseTracker() ;
int tipid = 0;
if(request.getParameter("tipid") != null)
{
tipid = Integer.parseInt(request.getParameter("tipid"));
}
if (tipid == 0){ response.sendRedirect("/MASC/index.jsp");}
%>
<h1> Tip report for <% out.print(tracker.getDateStringByTipId(tipid));
tracker.finalize();%></h1>
<%if(request.getParameter("failed") != null)
{
%> <br><font color=\"red\"> Login failed</font> <%
}
%>
<form action="ResponseDB" method="post">
<input name="tipid" id="tipid" value="<% out.println(tipid);%>">
Any events to report?
<label><input type="radio" name="events" onclick="checkEvent(this.value,if_events_yes,submit)" id="events_yes" value="yes">Yes</label>
<label><input type="radio" name="events" onclick="checkEvent(this.value,if_events_yes,submit)" id="events_no" value="no" checked>No</label>
<fieldset id="if_events_yes">
<label>Firewall:<br>
<textarea name="firewall"></textarea></label>
<label>IDS/IPS:<br>
<textarea name="ids"></textarea></label>
<label>Web Content Filtering/Proxy:<br>
<textarea name="proxy"></textarea></label>
<label>Deep packet inspection:<br>
<textarea name="dpi"></textarea></label>
<label>Network malware protection devices (FireEye, Damballa, etc.):<br>
<textarea name="net_malware"></textarea></label>
<label>Anti-virus software:<br>
<textarea name="av"></textarea></label>
<label>Forensics Tools:<br>
<textarea name="forensics"></textarea></label>
<label>Tripwire:<br>
<textarea name="tripwire"></textarea></label>
<label>Memory Dumps:<br>
<textarea name="memdumps"></textarea></label>
<label>Email logs:<br>
<textarea name="email_logs"></textarea></label>
</fieldset>
<input type="submit" id="submit" value="Submit">
</form>
<script>
function checkEvent(el,y,s) {
console.log("infunc");
if (el == 'yes') {
y.style.display = "block";
s.className = "active";
}
else {
y.style.display = "none";
s.className = "";
}
}
onsubmit=function() {
if (document.getElementById('events_yes').checked == true) {
var t = document.getElementsByTagName("textarea"),
l = 0;
for(var i = 0; i < t.length; i++){
l = l + t[i].value.trim();
}
if (l < 1) {
alert("Please re-enter");
return false;
}
}
}
</script>
</body>
</html>
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>
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.
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;
*Edit: Fixed so that all inputs are now validated on one form. However, I can only add one variable to check if blank, as soon as I add more, none of the submit functions work. I have been trying multiple things.
function validateForm() {
var inputVelocity = document.getElementById("dzCalculator").inputVelocity.value;
var inputYellowPhase = document.getElementById("dzCalculator").inputYellowPhase.value;
var inputRedPhase = document.getElementById("dzCalculator").inputInterPhase.value;
var inputReactionTime = document.getElementById("dzCalculator").inputReactionTime.value;
if(inputVelocity === "" && inputYellowPhase === "" && inputRedPhase === "" && inputReactionTime === ""){
alert("Input all fields to calculate.");
return false;
}
}
I have checked the HTML matches - it does. But I found I could not use onsubmit="return validateForm" as this wouldn't work at all.
This is only 4 of the form values, there are seven all up. But when I can get the four working, I can get them all working.
How can I use JS to make sure that no input is left blank or empty? I already have made it so that it will only accept numbers and decimal points. So no one can add an incorrect field. But currently, they can leave a field blank which means my calculator generates a NaN response.
Also, how can I make sure one of my fields can not accept a number greater than 1 or less than 0. I tried min="0" max="1" in the input tag, but because I have removed spinners, this doesn't work.
So, in summary, I am looking to make sure when a button is clicked that all the form sections are filled in and that one of the fields doesn't accept a number greater that 1 or less than zero.
there are 2 options for this.
You can select all the inputs (inside the form tag) using querySelector and check the value of each input by looping through them.
use this trick selector to get all the invalid inputs
document.querySelectorAll('input:not([value]):not([value=""])');
replace input with more precise selector.
Can you please give more detail about how your form is in multiple places?
For input I think you need to use step attribute
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step
Reference: javascript_form_validation
Depends when would you like to validate form fields
For example: Form validation on submit
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<html>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Give name to your form using name attribute such as <form name="myForm" ..>
Then using document.forms["myForm"] you can have access to your form
There you can validate your input fields value. return true if validates
This works for me. You can use it, style it however you want or not. You do need JQuery. It has powerful selectors.
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
body{
font-size: 12px;
}
.main-container{
display: flex; /* DO NOT CHANGE */
height: 100vh; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
}
.c-message{
display: flex; /* DO NOT CHANGE */
position: fixed; /* DO NOT CHANGE */
top: 0px; /* DO NOT CHANGE */
left: 0px; /* DO NOT CHANGE */
width: 100%; /* DO NOT CHANGE */
height: 100%; /* DO NOT CHANGE */
}
.c-msgbox{
padding: 30px;
text-align: center;
margin: auto; /* DO NOT CHANGE */
background-color: #e4e4e4;
border-radius: 4px;
border: 1px solid #adadad;
-webkit-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
-moz-box-shadow: 0px 0px 50px rgba(0, 0, 0, 0.60);
box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.40);
}
.standerd-button2{
border: none;
font-family: arial,helvetica,clean,sans-serif;
font-size: 10px;
font-weight: 600;
color: white;
background: #1A709F;
padding: 3px;
text-align: center;
vertical-align: middle;
-webkit-border-radius: 3px;
width: max-content;
min-width: 50px;
margin: 2px;
}
.standerd-button2:hover{
background: crimson;
cursor: default;
}
.f-table {
display: table;
width: max-content;
padding: 5px;
border-spacing: 2px;
}
.f-tablerow {
display: table-row;
}
.f-tablecell{
display: table-cell;
}
.label-cell-r{
text-align: right;
}
.dd-required{
margin: auto;
color: red;
}
input, select{
border: 1px solid lightgrey;
}
</style>
<script type="text/javascript" src="JQuery.js"></script>
</head>
<body>
<div class="main-container">
<div>
<form id="f1" name="f1">
<div class="f-table">
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="firstname">First Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="firstname" name="firstname" type="text" data-er="First Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="lastname">Last Name</label>
</div>
<div class="f-tablecell input-cell">
<input id="lastname" name="lastname" type="text" data-er="Last Name"/>
<span class='dd-required'>*</span>
</div>
</div>
<div class="f-tablerow">
<div class="f-tablecell label-cell-r">
<label for="company">Company</label>
</div>
<div class="f-tablecell input-cell">
<select id="company" name="company" data-er="Company Name">
<option value="0"> - Select Comapny - </option>
<option value="1">Company 1</option>
<option value="2">Company 2</option>
<option value="3">Company 3</option>
<option value="4">Company 4</option>
</select>
<span class='dd-required'>*</span>
</div>
</div>
</div>
<input id="b1" type="submit" value="Submit" />
</form>
</div>
<div>
<script type="text/javascript">
$.fn.CustomAlert = function (options, callback) {
var settings = $.extend({
message: null,
detail: null,
yesno: false,
okaytext: null,
yestext: null,
notext: null
}, options);
var frm = "";
detail = "<b>" + settings.detail + "</b>";
message = "<b>" + settings.message + "</b>";
if (settings.detail === null) {
detail = "";
};
frm = frm + message + "<div style='text-align: left; margin-top: 15px; margin-bottom: 15px;'>" + detail + "</div>";
if (settings.yesno === false) {
frm = frm + "<input id='ok' type='button' value='" + settings.okaytext + "' class='standerd-button2' />";
} else {
frm = frm + "<div><input id='yes' type='button' value='" + settings.yestext + "' name='yes' class='standerd-button2' />" +
"<input id='no' type='button' value='" + settings.notext + "' name='no' class='standerd-button2' /></div>";
};
var frmesg = "<div id='cmessage' name='cmessage' class='c-message'>" +
"<div class='c-msgbox'>" +
"<form>" + frm + "</form>" +
"</div>" +
"</div>";
$(".main-container").append(frmesg);
if (!settings.yesno) {
$("#cmessage #ok").click(function () {
$("#cmessage").remove();
callback(false);
});
} else {
$("#cmessage #yes").click(function () {
$("#cmessage").remove();
callback(true);
});
$("#cmessage #no").click(function () {
$("#cmessage").remove();
callback(false);
});
};
};
$.fn.JsFormCheck = function () {
var MessData = "";
this.find('select, input').each(function () {
if ($(this).attr("data-er")) {
m = $(this).attr("data-er");
switch ($(this).get(0).tagName) {
case "INPUT":
if ($(this).val().length === 0) {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
case "SELECT":
if ($(this).val() === "0") {
MessData = MessData + "- " + m + "<br>";
$(this).css('border-bottom', '2px solid green');
};
break;
};
};
});
if (MessData.length > 0) {
MessData = "<b>" + MessData + "</b>";
x = $().CustomAlert({message: "<b>Please fill in the following required fields to continue.</b>",
detail: MessData,
okaytext: "Close",
yesno: false});
return true;
} else {
return false;
};
};
$('#f1 #b1').click(function(event){
event.preventDefault();
Error = $("#f1").JsFormCheck();
if(Error === false){
null;
//Do Something
};
});
</script>
</body>
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.");
}
});
});