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 ;
Related
My problem is that I'd like the color to switch depending on what the value is, either odd, even or just 0. I've search on stackoverflow for some answers but none really helped..
So, if the answer is odd, the color shall be blue. If the answer is even, the color shall be red. If the answer is 0, the color shall be yellow.
Any clues that could help me keep going?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body {
background-color: #0D1112;
}
form {
display: flex;
height: 30px;
gap: 30px;
align-items: center;
justify-content: center;
}
p {
color: white;
}
h1 {
color: white;
text-align: center;
}
#svar {
background-color: #0D1112;
}
h4 {
color: white;
}
</style>
</head>
<body>
<form id="f0rm">
<input name="nummer1" id="nummer1" type="text" size="5">
<select id="dropDown" name="thing" id="dropID">
<option>choose</option>
<option value="+">+</option>
<option value="-">-</option>
<option value="x">x</option>
<option value="/">/</option>
</select>
<input name="nummer2" id="nummer2" type="text" size="5"> =
<input type="button" id="calculator" value="Submit">
</form>
<div id="svar">
<p>Your answer is...</p>
<h4>Blue = odd answer</h4>
<h4>Red = even answer</h4>
<h4>Yellow = your answer is just 0</h4>
</div>
<script>
$(function() {
$('#calculator').click(function() {
var value = $("#dropDown").val();
var number1 = $("#nummer1").val();
var number2 = $("#nummer2").val();
var int1 = parseInt(number1);
var int2 = parseInt(number2);
if (value === "+") $("#svar p").text(int1 + int2);
else if (value === "-") $("#svar p").text(int1 - int2);
else if (value === "/") $("#svar p").text(int1 / int2);
else if (value === "x") $("#svar p").text(int1 * int2);
if (value % 2 == 0)
$("#svar p").css("background-color", "red")
else(value % 2 == 1)
$("#svar p").css("background-color", "blue")
});
});
</script>
</body>
</html>
Just debugged your code a little bit
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body {
background-color: #0D1112;
}
form {
display: flex;
height: 30px;
gap: 30px;
align-items: center;
justify-content: center;
}
p {
color: white;
}
h1 {
color: white;
text-align: center;
}
#svar {
background-color: #0D1112;
}
h4 {
color: white;
}
</style>
</head>
<body>
<form id="f0rm">
<input name="nummer1" id="nummer1" type="text" size="5">
<select id="dropDown" name="thing" id="dropID" required>
<option>choose</option>
<option value="+">+</option>
<option value="-">-</option>
<option value="x">x</option>
<option value="/">/</option>
</select>
<input name="nummer2" id="nummer2" type="text" size="5"> =
<input type="button" id="calculator" value="Submit">
</form>
<div id="svar">
<p>Your answer is...</p>
<h4>Blue = odd answer</h4>
<h4>Red = even answer</h4>
<h4>Yellow = your answer is just 0</h4>
</div>
<script>
$(function() {
$('#calculator').click(function() {
var value = $("#dropDown").val();
var number1 = $("#nummer1").val();
var number2 = $("#nummer2").val();
var int1 = parseInt(number1);
var int2 = parseInt(number2);
let result = 0;
if (value === "+") result = int1 + int2;
else if (value === "-") result = int1 - int2;
else if (value === "/") result = int1 / int2;
else if (value === "x") result = int1 * int2;
$("#svar p").text(result)
if (result % 2 == 0){
$("#svar p").css("background-color", "red");
} else {
$("#svar p").css("background-color", "blue");
}
});
});
</script>
</body>
</html>
I have to get the value of .qty input field but I have a problem that another jQuery function is rewriting the entered value after it gets entered.
For instance, if I enter 1, it gets rounded to 3,3360 but multiplied by 1 so I only can get the written value but I need the value that is changed after (3,3360) and the result should be 33.36 not 10.00:
function myFunctionupdateqtyinput() {
var x = document.getElementById("quantity_60269d6f09cd1");
var a = 3.336;
var b = x.value;
var d = b - (b % a) + a;
var f = d.toPrecision(5);
x.value = f;
}
if ($(".kpt-product-count").length) {
function checkForCount() {
var single_count = parseFloat($(".kpt-product-count").data('kptcount'));
var qty = parseFloat($(".qty").val());
var total = (qty * single_count);
total = total.toFixed(2);
if (isNaN(total)) {
total = single_count.toFixed(2);
}
$(".kpt-product-count-text").find('span').html(total);
}
$(".qty").on('input', checkForCount);
}
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce.css");
.quantity .qty {
height: 34px;
}
.quantitym2 .qty {
width: 90;
margin-right: 10;
}
.kpt-product-count {
display: inline-flex;
font-size: 15px;
margin-top: 15px;
}
.kpt-product-count-label {
font-weight: 600;
padding-right: 10px;
}
.quantitym2 input::-webkit-inner-spin-button {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity quantitym2">
<label class="screen-reader-text" for="quantity_60269d6f09cd1">Boost quantity</label>
<input type="number" onchange="myFunctionupdateqtyinput()" id="quantity_60269d6f09cd1" class="input-text qty text" value="3.336" step="0.0001" min="0.0001" max="" name="quantity" title="title" size="4" placeholder="" inputmode="">
</div>
<div class="kpt-product-count" data-kptcount="10">
<div class='kpt-product-count-label'>In total: </div>
<div class='kpt-product-count-text'> <span>10</span> </div>
</div>
You need to call the function myFunctionupdateqtyinput()inside the checkForCount function
function checkForCount() {
myFunctionupdateqtyinput();
function myFunctionupdateqtyinput() {
var x = document.getElementById("quantity_60269d6f09cd1");
var a = 3.336;
var b = x.value;
var d = b - (b % a) + a;
var f = d.toPrecision(5);
x.value = f;
}
if ($(".kpt-product-count").length) {
function checkForCount() {
myFunctionupdateqtyinput();
var single_count = parseFloat($(".kpt-product-count").data('kptcount'));
var qty = parseFloat($(".qty").val());
var total = (qty * single_count);
total = total.toFixed(2);
if (isNaN(total)) {
total = single_count.toFixed(2);
}
$(".kpt-product-count-text").find('span').html(total);
}
$(".qty").on('input', checkForCount);
}
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-layout.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce-smallscreen.css");
#import url("https://tonicuk.com/wp-content/plugins/woocommerce/assets/css/woocommerce.css");
.quantity .qty {
height: 34px;
}
.quantitym2 .qty {
width: 90;
margin-right: 10;
}
.kpt-product-count {
display: inline-flex;
font-size: 15px;
margin-top: 15px;
}
.kpt-product-count-label {
font-weight: 600;
padding-right: 10px;
}
.quantitym2 input::-webkit-inner-spin-button {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="quantity quantitym2">
<label class="screen-reader-text" for="quantity_60269d6f09cd1">Boost quantity</label>
<input type="number" onchange="myFunctionupdateqtyinput()" id="quantity_60269d6f09cd1" class="input-text qty text" value="3.336" step="0.0001" min="0.0001" max="" name="quantity" title="title" size="4" placeholder="" inputmode="">
</div>
<div class="kpt-product-count" data-kptcount="10">
<div class='kpt-product-count-label'>In total: </div>
<div class='kpt-product-count-text'> <span>10</span> </div>
</div>
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>
The page should output and execute a temperature converter...
However,
While I'm wanting to test my program, I keep running into this a blank page type error...
can someone kind of proof read this, because I don't know what I'm missing.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var convertTemp = function(){
var f;
var c;
if($("to_Celsius").checked){
f = parseFloat($("degrees_entered").value);
if(isNaN(f)){
alert("please type in a value ");
}
else{
c = (f-32) * 5/9;
$("degrees_computed").value = c.toFixed(0);
}
}
else{
c = parseFloat($("degrees_entered").value);
if(isNaN(c)){
alert("you must enter a valid number for degrees.");
}
else{
f = c * 9/5 + 32;
$("degrees_computed").value = f.toFixed(0);
}
}
};
var toFahrenheit = function(){
$("degree_label_1").firstChild.nodeValue = "Enter C degrees:";
$("degree_label_2").firstChild.nodeValue = "Degrees F";
clearTextBoxes();
$("degrees_entered").focus();
};
var toCelsius = function(){
$("degree_label_1").firstChild.nodeValue = "Enter F degrees: ";
$("degree_label_2").firstChild.nodeValue = "Degrees C: ";
clearTextBoxes();
$("degrees_entered").focus();
};
var clearTextBoxes = function(){
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function(){
$("convert").onclick = convertTemp;
$("to_Celsius").onclick != toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>
toCelcius != toCelsius ?
Is that it? A silly typo? The rest looks fine... also watch casing. In your JS you have to_Celsius... but in the html... to_celcius... bad habit for sure
Some issues I verified:
in the line if($("to_Celsius").checked){ you refer to to_Celsius id, but it should be to_celsius (lowercase);
in the lines:
$("to_Celsius").onclick = toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
Same thing. Replace both the id with to_celsius and to_fahrenheit.
in this line var toCelcius = function(){, the function is named toCelcius. Just rename it to toCelsius (with s).
Working code: https://jsfiddle.net/mrlew/p8w111ms/
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>