HTML and javascript username validation - javascript

For my school project we have to make a sign up page and check if the input is valid.
This is my code so far but the validity check won't work.
I am trying to make a button that checks validity and turns another button into submit but it wont work for some reason.
function CheckAll() {
var flag = true;
var length = document.getElementById('user').value.length;
var value = document.getElementById('user').value;
for (var i = 0; i < length; i++) {
if (!(value.charAt(i) >= '0' && value.charAt(i) <= '9') || (value.charAt(i) >= 'a' && value.charAt(i) <= 'z') || (value.charAt(i) >= 'A' && value.charAt(i) <= 'Z')) {
alert("username must be made of characters and numbers only");
flag = false;
}
}
var lengthPass = document.getElementById('password').value.length;
var valuePass = document.getElementById('password').value;
for (var i = 0; i < lengthPass; i++) {
if (!(valuePass.charAt(i) >= '0' && valuePass.charAt(i) <= '9') || (valuePass.charAt(i) >= 'a' && valuePass.charAt(i) <= 'z') || (valuePass.charAt(i) >= 'A' && valuePass.charAt(i) <= 'Z')) {
alert("Password must be made of characters and numbers only");
flag = false;
}
}
if (!(length >= 6 || length <= 20)) {
alert("Username Must be 6-20 Characters long");
}
if (!(lengthPass >= 6 || lengthPass <= 20)) {
alert("Password must be 6-20 characters long")
flag = true;
}
var valueMail = document.getElementById("mail").value;
var check = false;
var shtrudel = 0;
for (var i = 0; i < valueMail.length; i++) {
if (value.chatAt(i) == '#') {
shtrudel++;
for (var j = i; j < valueMail.length; j++) {
if (valueMail.charAt(j) == '.') {
check = true;
}
}
}
}
if (shtrudel > 1) {
alert("You're only allowed to have 1 '#' sign");
}
if (!check) {
alert("Your email has to include a '#' sign and a '.' sign");
}
var valuePhone = document.getElementById('phone').value;
var lengthPgone = document.getElementById('phone').value.length;
for (var i = 0; i < length; i++) {
if (!((valuePhone.charAt(i) >= '0' || valuePhone.charAt(i) <= '9') && (valuePhone.length != 7))) {
flag = false;
}
}
// ------ missing a } ----- //
function AgreeCheck() {
var Check = document.getElementById("agree").checked;
var Button = document.getElementById("submit");
if (Check && (CheckAll)) {
Button.setAttribute("type", "submit");
Button.removeAttribute("style");
} else {
Button.setAttribute("type", "button");
Button.setAttribute("style", "color:grey");
}
}
html {
background-image: url("Images/cup630.jpg");
background-repeat: no-repeat;
background-size: cover;
height: 150%;
}
form {
color: red
}
input[type=text],
input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
.cancelbtn,
.signupbtn {
float: left;
width: 50%;
}
.container {
padding: 16px;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
#media screen and (max-width: 300px) {
.cancelbtn,
.signupbtn {
width: 100%;
}
}
<form action="HomePage.html" id="form">
Name+Last Name: <input type="text" name="names" />
<br />
<br /> Username: <input type="text" name="username" id="user" />
<br />
<p style="font-size:70%">must contain 6-20 character</p>
<br /> Password: <input type="text" name="password" id="password" />
<br />
<p style="font-size:70%">must contain 6-20</p>
<br /> E-mail: <input type="text" name="mail" id="mail" />
<br /> Phone Number: <input type="text" name="phone" id="phone" />
<br /> Enter Your Birth Date:
<br />
<br /> Day <input type="text" name="day" /> Month <input type="text" name="month" /> Year <input type="text" name="year" />
<br />
<br />
<br /> Enter Your Favourite Esports Game:
<select>
<option>League Of Legends</option>
<option>Dota</option>
<option>StarCraft</option>
<option>Street Fighter</option>
<option>Smite</option>
<option>Mortal Kombat</option>
<option>Heroes Of The Storm</option>
<option>Super Smash Bros</option>
<option>Call of Duty</option>
<option>Counter Strike: Global Offensive</option>
<option>I Dont Watch Esports</option>
</select>
<br />
<br />
<input type="button" name="agree" id="agree" value="check validity" onclick="AgreeCheck()" />
<input type="button" name="submit" id="submit" value="submit" />
</form>

Several issues
you are missing a } - look at the code and the console. I marked it // <------ missed a } here in my code
NEVER call anything is a form "submit" since it hides the submit event
You expect to use a checkbox, so use a checkbox
Set the submit to disabled instead of changing style and type
You need to return false or true from checkAll
This code is not complete. Fix the above stuff first and then see why you alert the same thing twice
function CheckAll() {
var flag = true;
var length = document.getElementById('user').value.length;
var value = document.getElementById('user').value;
for (var i = 0; i < length; i++) {
if (!(value.charAt(i) >= '0' && value.charAt(i) <= '9') || (value.charAt(i) >= 'a' && value.charAt(i) <= 'z') || (value.charAt(i) >= 'A' && value.charAt(i) <= 'Z')) {
alert("username must be made of characters and numbers only");
return false;
}
}
var lengthPass = document.getElementById('password').value.length;
var valuePass = document.getElementById('password').value;
for (var i = 0; i < lengthPass; i++) {
if (!(valuePass.charAt(i) >= '0' && valuePass.charAt(i) <= '9') || (valuePass.charAt(i) >= 'a' && valuePass.charAt(i) <= 'z') || (valuePass.charAt(i) >= 'A' && valuePass.charAt(i) <= 'Z')) {
alert("Password must be made of characters and numbers only");
return false;
}
}
if (!(length >= 6 || length <= 20)) {
alert("Username Must be 6-20 Characters long");
return false;
}
if (!(lengthPass >= 6 || lengthPass <= 20)) {
alert("Password must be 6-20 characters long")
return false
}
var check = false;
var valueMail = document.getElementById("mail").value;
var shtrudel = 0;
for (var i = 0; i < valueMail.length; i++) {
if (value.chatAt(i) == '#') {
shtrudel++;
for (var j = i; j < valueMail.length; j++) {
if (valueMail.charAt(j) == '.') {
check = true;
}
}
}
}
if (shtrudel > 1) {
alert("You're only allowed to have 1 '#' sign");
return false
}
if (!check) {
alert("Your email has to include a '#' sign and a '.' sign");
return false;
}
var valuePhone = document.getElementById('phone').value;
var lengthPgone = document.getElementById('phone').value.length;
for (var i = 0; i < length; i++) {
if (!((valuePhone.charAt(i) >= '0' || valuePhone.charAt(i) <= '9') && (valuePhone.length != 7))) {
return false;
}
}
return true;
} // <------ missed a } here
function AgreeCheck() {
document.getElementById("agree").checked = CheckAll();
document.getElementById("sub").disabled = !CheckAll();
}
html {
background-image: url("Images/cup630.jpg");
background-repeat: no-repeat;
background-size: cover;
height: 150%;
}
form {
color: red
}
input[type=text],
input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
.cancelbtn,
.signupbtn {
float: left;
width: 50%;
}
.container {
padding: 16px;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
#media screen and (max-width: 300px) {
.cancelbtn,
.signupbtn {
width: 100%;
}
}
<form action="HomePage.html" id="form">
Name+Last Name: <input type="text" name="names" />
<br />
<br /> Username: <input type="text" name="username" id="user" />
<br />
<p style="font-size:70%">must contain 6-20 character</p>
<br /> Password: <input type="text" name="password" id="password" />
<br />
<p style="font-size:70%">must contain 6-20</p>
<br /> E-mail: <input type="text" name="mail" id="mail" />
<br /> Phone Number: <input type="text" name="phone" id="phone" />
<br /> Enter Your Birth Date:
<br />
<br /> Day <input type="text" name="day" /> Month <input type="text" name="month" /> Year <input type="text" name="year" />
<br />
<br />
<br /> Enter Your Favourite Esports Game:
<select>
<option>League Of Legends</option>
<option>Dota</option>
<option>StarCraft</option>
<option>Street Fighter</option>
<option>Smite</option>
<option>Mortal Kombat</option>
<option>Heroes Of The Storm</option>
<option>Super Smash Bros</option>
<option>Call of Duty</option>
<option>Counter Strike: Global Offensive</option>
<option>I Dont Watch Esports</option>
</select>
<br />
<br />
<input type="checkbox" name="agree" id="agree" value="check validity" onclick="AgreeCheck()" />
<input type="submit" name="sub" id="sub" value="submit" disabled/>
</form>

Related

How to set specific text input be not required to fill in

First of all i'm a newbie of programming . I want to create a mini project using multiform. I use example from https://www.w3schools.com/howto/howto_js_form_steps.asp but i wonder how to set specific text input be not required to fill in for proceed the process of submit the data. Sorry for asking.
This is the code from W3S but the validation code is changed.
If you look in the code you will find commented fields with many !!! this is the validator
EDIT:
Currently the field for "Last name" i added an attribute data="noverify" Currently, any field that has this attribute will not be required.
In this example: First name is required. A Last name is NOT required!
Add this attribute data="noverify" for all fields you want NOT to be required!
This check y[i].getAttribute('data') !== "noverify" is made below in the code to skip the fields with data="noverify"
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<style>
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
</style>
<body>
<form id="regForm" action="/action_page.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." oninput="this.className = ''" name="fname"></p>
<p><input data="noverify" placeholder="Last name..." oninput="this.className = ''" name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." oninput="this.className = ''" name="email"></p>
<p><input placeholder="Phone..." oninput="this.className = ''" name="phone"></p>
</div>
<div class="tab">Birthday:
<p><input placeholder="dd" oninput="this.className = ''" name="dd"></p>
<p><input placeholder="mm" oninput="this.className = ''" name="nn"></p>
<p><input placeholder="yyyy" oninput="this.className = ''" name="yyyy"></p>
</div>
<div class="tab">Login Info:
<p><input placeholder="Username..." oninput="this.className = ''" name="uname"></p>
<p><input placeholder="Password..." oninput="this.className = ''" name="pword" type="password"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
if (y[i].getAttribute('data') !== "noverify") {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
}
// If the valid status is true, mark the step as finished and valid:
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
</script>
</body>
</html>
you can use value for set default text value
<div class="tab">Name:
<p><input placeholder="First name..." value="One" oninput="this.className = ''"></p>
<p><input placeholder="Last name..." value="Two" oninput="this.className = ''"></p>
</div>

Adding a default number to JavaScript [duplicate]

This question already has answers here:
Convert NaN to 0 in JavaScript
(11 answers)
Closed 2 years ago.
I have a program I am working on that is supposed to be a makeshift discount calculator. I keep getting NaN when I try to make the program run without any input. I would like to add in a line of code that makes zero the default instead of Nan. I'm not sure what to do and any help would be appreciated!
"use strict";
var $ = function(id) { return document.getElementById(id); };
var calculateDiscountPercent = function(customerType, invoiceSubtotal) {
var discountPercent = 0;
if (customerType === "r") {
if (invoiceSubtotal < 100) {
discountPercent = .0;
} else if (invoiceSubtotal >= 100 && invoiceSubtotal < 250) {
discountPercent = .1;
} else if (invoiceSubtotal >= 250 && invoiceSubtotal < 500) {
discountPercent = .25;
} else if (invoiceSubtotal >= 500) {
discountPercent = .3;
}
} else if (customerType === "l") {
discountPercent = .3;
} else if (customerType === "h") {
if (invoiceSubtotal < 500) {
discountPercent = .4;
} else if (invoiceSubtotal >= 500) {
discountPercent = .5;
}
}
return discountPercent;
};
var processEntries = function() {
var discountAmount;
var invoiceTotal;
var discountPercent;
//get values from page, reset subtotal to 2 decimals
var customerType = $("type").value;
var invoiceSubtotal = parseFloat( $("subtotal").value );
$("subtotal").value = invoiceSubtotal.toFixed(2);
//call function to get discount percent
discountPercent = calculateDiscountPercent(customerType, invoiceSubtotal);
//calculate and display discount percent, amount, and new total
discountAmount = invoiceSubtotal * discountPercent;
invoiceTotal = invoiceSubtotal - discountAmount;
$("percent").value = (discountPercent * 100).toFixed(2) ;
$("discount").value = discountAmount.toFixed(2);
$("total").value = invoiceTotal.toFixed(2);
$("type").focus;
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("type").focus();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 500px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 10em;
}
input, select {
width: 12em;
margin-left: 1em;
margin-bottom: .5em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Invoice Total Calculator</title>
<link rel="stylesheet" type="text/css" href="invoice_total.css">
<script type="text/javascript" src="invoice_total.js"></script>
</head>
<body>
<main>
<h1>Invoice Total Calculator</h1>
<p>Enter the two values that follow and click "Calculate".</p>
<label for="type">Customer Type:</label>
<select id="type">
<option value="r">Regular</option>
<option value="l">Loyalty Program</option>
<option value="h">Honored Citizen</option>
</select>
<br>
<label for="subtotal">Invoice Subtotal:</label>
<input type="text" id="subtotal" /><br>
----------------------------------------------------------------<br>
<label for="percent">Discount Percent:</label>
<input type="text" id="percent" disabled />%<br>
<label for="discount">Discount Amount:</label>
<input type="text" id="discount" disabled /><br>
<label for="total">Invoice Total:</label>
<input type="text" id="total" disabled /><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" />
</main>
</body>
</html>
Do this
var invoiceSubtotal = parseFloat( $("subtotal").value ) || 0 ;

Need to add function to make sure at least 1 checkbox is selected before submitting multipage form?

I am working on a form with multiple pages. On one page I have check boxes that I would require at least one to be selected before submission. How can I do that with javascript/html5?
It is all one form that changes pages with javascript. How on the last page can I have the form check, if at least one checkbox has been selected?
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
<form id="regForm" action="/action_page.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." oninput="this.className = ''" name="fname"></p>
<p><input placeholder="Last name..." oninput="this.className = ''" name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." oninput="this.className = ''" name="email"></p>
<p><input placeholder="Phone..." oninput="this.className = ''" name="phone"></p>
</div>
<div class="tab">
<H3 id="subhead">AUDITORIUM ROOM SETUP & EQUIPMENT REQUESTS</H3>
<label><label id="asterisk">*</label>Room Setup (Select all that apply):</label><br><br>
<!-- <p><input placeholder="dd" oninput="this.className = ''" name="dd"></p> -->
<br>
<input id="element_3_1" name="Room-Setup" required type="checkbox" value="Auditorium-Seating-for-300" />
<label class="choice" id="labelinput" for="element_3_1">Auditorium Seating for 300</label>
<br>
<input id="element_3_2" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Auditorium-Seating-for-350" />
<label class="choice" id="labelinput" for="element_3_2">Auditorium Seating for 350 (recommended max for Performances</label>
<label class="choice" for="element_3_3">Auditorium Seating 400</label>
<input id="element_3_3" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Auditorium-Seating-400" />
<label class="choice" for="element_3_4">Round Tables and Chairs</label>
<input id="element_3_4" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Round-Tables-and-Chairs" />
<label class="choice" for="element_3_5">Other (Please note that we cannot change the auditorium setup during your event*)</label>
<input id="element_3_5" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Other" />
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
Put a second classname in <div class="tab theFirstTabWithCheckboxes">
This code get that element and counts cheched inputs to a global variable
var checkboxes = document.querySelectorAll("tab.theFirstTabWithCheckboxes input");
var i = checkboxes.length;
window.count_nr_of_checked_boxes = 0;
while (i--) { //count down to 0
if (checkboxes[i].checked) window.count_nr_of_checked_boxes++;
}
With querySelectorAll() you select in the same way as you select in CSS. Note how the dot operator is an and operator and the space operator means "input is inside ..." (it is evaluated from right to left).
Put the following line in the function validateForm()
if (count_nr_of_checked_boxes < 1) valid = false
You dont need to have window. on global variables

Captcha Code in JavaScript is not working

I have a validation Form using Javascript. It must validate the name, email and captcha. But through my validation function, the name and email are validated but the captcha is not validated after the onclick of the submit button.
The following functions shows my code:
<script type="text/javascript">
function validateform(){
var cm_name=document.supportus_form.cm_name.value;
var cm_email=document.supportus_form.cm_email.value;
var atpos = cm_email.indexOf("#");
var dotpos = cm_email.lastIndexOf(".");
if (cm_name==null || cm_name=="")
{
alert("Name can't be blank");
return false;
}
else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var why = "";
if(theform.CaptchaInput.value == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(theform.CaptchaInput.value != ""){
if(ValidCaptcha(theform.CaptchaInput.value) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;
// Validate input against the generated number
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('CaptchaInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
} </script>
The following is my html code for the form which i am using:
<form class="form-horizontal" role="form" action='<?php echo
site_url(); ?>/Welcome/insert_support_info' method="post" enctype="multipart/form-data" onsubmit="return validateform()" name="supportus_form">
<br style="clear:both"/>
<h3 style="margin-bottom: 25px; text-align: center;"><u>Let us Know your Interest</u></h3>
<div class="form-group">
<input type="text" class="form-control" name="cm_name" id="fullname" placeholder="Enter Your Name"/>
<input type="text" class="form-control" name="cm_email" id="email" placeholder="Enter Your E-Mail"/>
<input type="text" class="form-control" name="cm_phone" id="phone" placeholder="Enter Your Phone Number or Mobile Number"/>
<textarea class="form-control" name="cm_message" id="message" rows="3" placeholder="Add your Query"></textarea>
<span class="help-block"><p id="characterLeft" class="help-block ">Limit - 100 words</p></span>
<input class="form-control" name="datetime" value="<?php
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y h:i:s a', time()); echo $date;
?>" type="hidden" />
<!-- START CAPTCHA -->
<br>
<div class="capbox">
<div id="CaptchaDiv"></div>
<div class="capbox-inner">
Type the above number:<br>
<input type="hidden" id="txtCaptcha">
<input type="text" name="CaptchaInput" id="CaptchaInput" size="15"><br>
</div>
</div>
<br><br>
<!-- END CAPTCHA -->
<button type="submit" class="btn btn-success">Submit</button>
</div>
<hr/>
</form>
I have kept the css to show up the captcha form
<style>
.capbox {
background-color: #92D433;
border: #B3E272 0px solid;
border-width: 0px 12px 0px 0px;
display: inline-block;
*display: inline; zoom: 1; /* FOR IE7-8 */
padding: 8px 40px 8px 8px;
}
.capbox-inner {
font: bold 11px arial, sans-serif;
color: #000000;
background-color: #DBF3BA;
margin: 5px auto 0px auto;
padding: 3px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
#CaptchaDiv {
font: bold 17px verdana, arial, sans-serif;
font-style: italic;
color: #000000;
background-color: #FFFFFF;
padding: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
#CaptchaInput { margin: 1px 0px 1px 0px; width: 135px; }
</style>
With the Above code, the captcha is not working. I am using captcha for the first time.
Hey You are using conditional tags in improper way . That leads to unknown bugs. Following Javascript code works you correct.
function validateform(){
var cm_name=document.supportus_form.cm_name.value;
var cm_email=document.supportus_form.cm_email.value;
var atpos = cm_email.indexOf("#");
var dotpos = cm_email.lastIndexOf(".");
var captha = document.getElementById("txtCaptcha").value;
var capthaValue = document.getElementById('CaptchaInput').value.replace(/ /g,'');
console.log(typeof captha);
if(capthaValue == "" || captha != capthaValue) {
validCaptcha()
}
if (cm_name==null || cm_name=="")
{
alert("Name can't be blank");
return false;
}
else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
function validCaptcha() {
var why = "";
if(capthaValue == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(capthaValue != ""){
if((captha != capthaValue) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;

If I add new form elements (appendChild) a form, I can't add event

I made a program when you enter form field number, you can insert a plus input box if you fell, whem remove. A problem is that we have a for loop, where you can gather elements which the "validate" class is (these form fields). onblur event to add functions, but I can not solve that added new elements to the program take into account. I tried and I did arrays that included new elements into an array, but since the for loop is therefore outside the event, if you add it, you can do nothing happens.
If anyone can help that in that case, it wont solve this, I really appreciate it!
(A code is supplied, only a test, specifically focuses on this problem.)
function onlyNumber(e) {
var x = e.keyCode;
if ((x >= 49 && x <= 57) || x === 9 || x === 8 || x === 46 || (x >= 97 && x <= 105)) {
return true;
} else {
e.preventDefault();
}
}
function initOnlyNumber() {
var el = document.querySelectorAll('.onlynumber');
for (var i = 0; i < el.length; i++) {
el[i].addEventListener('keydown', onlyNumber, false);
}
}
var childNumber = document.querySelector('.childNumber');
childNumber.onkeyup = function() {
var childNumberValue = childNumber.value;
var childrens = document.querySelector('.childrens');
var inputLengths = document.querySelectorAll('.kids');
var inputLength = '';
var element = '';
for (var i = 0; i < inputLengths.length; i++) {
var inputLength = inputLengths.length;
var element = inputLengths[i];
}
var arrayElement = [];
for (var i = inputLength; i < childNumberValue; i++) {
var newElement = document.createElement('input');
newElement.classList.add('kids');
newElement.classList.add('validate');
newElement.setAttribute('name', 'child-' + (i + 1));
newElement.setAttribute('data-name', 'child-' + (i + 1));
childrens.appendChild(newElement);
}
if (inputLength == 1) {
if (childNumberValue == '') {
childrens.removeChild(childrens.lastChild);
}
}
if (childNumberValue > 0) {
for (var i = inputLength; i > childNumberValue; i--) {
childrens.removeChild(childrens.lastChild);
}
}
}
var validates = document.querySelectorAll('.validate');
for (var i = 0; i < validates.length; i++) {
var validate = validates[i];
validate.onblur = function(event) {
obj = this;
console.log(obj);
}
}
window.onload = function() {
initOnlyNumber();
}
body {
margin: 20px;
padding: 0;
}
*:link,
*:hover,
*:visited,
*:focus {
outline: none;
}
input:-webkit-autofill {
color: #fff;
-webkit-box-shadow: 0 0 0px 1000px #4caf50 inset;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input {
background-color: #4caf50;
border: 1px solid #555;
color: #fff;
padding: 10px;
width: 50px;
}
.childrens {
display: inline-block;
}
.childrens input {
display: inline-block;
margin-left: 15px;
}
.childNumber {
background-color: #555;
}
<form action="">
<input class="validate onlynumber" name="name" type="text">
<br />
<br />
<input class="validate onlynumber" name="email" type="text">
<br />
<br />
<input class="validate onlynumber" name="tax" type="text">
<br />
<br />
<input class="validate onlynumber" name="phone" type="text">
<br />
<br />
<input class="childNumber onlynumber" name="childNumber" type="text" maxlength="1">
<div class="childrens"></div>
</form>

Categories