Deactivate a button until all javascript conditions have been checked - javascript

I´m trying to do different javascript validations before sending a form, the problem is that I haven´t been able to prevent the form from submit, it checks the conditions and sends alerts when a conditions hasn´t been satisfied but it sends the form anyways. I want the button to either be disabled until everything is right or send a message telling user, to check the cuenta.
Thanks in advance. This is my code:
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post">
Enter CLABE account:
<input name="clabe" id="clabe" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control" id="control" maxlength="1" size="2" required >
Again:
<input name="clabe2" id="clabe2" type = "text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente"/>
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr>
Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();" >
<hr>
Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="submit" id="myBtn" value="Guardar Cambios" onclick ="return compareclabe();" ><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
<script>
function compareclabe(){
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if( x3 != z3){
alert("keys are not equal");
return false;
}else if (x3 == z3){
this.someFunc(); //I want to call function someFunc and then
if the result is true, execute the next code
if (true){
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
return true;
}
}else{
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x,'37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10 ) {
digito_control = 0;
var dg = digito_control;
}else{
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z){
alert("checkig digit is not equal");
return false;
}
else if (dg == z){
alert("checkig digit is equal");
return true;
}
}
</script>

I changed form submit button type to "button" and if all the validations are passed, then submit form from javascript. See below code
function compareclabe() {
document.getElementById("myBtn").disabled = true;
var x1 = document.getElementById("clabe").value;
var x2 = document.getElementById("control").value;
var x3 = x1 + x2;
var z1 = document.getElementById("clabe2").value;
var z2 = document.getElementById("control2").value;
var z3 = z1 + z2;
if (x3 != z3) {
alert("keys are not equal");
return false;
} else if (x3 == z3) {
this.someFunc(); //I want to call function someFunc and then if the result is true, execute the next code
if (true) {
var cBanco = String(x3).charAt(0) + String(x3).charAt(1) + String(x3).charAt(2);
var x = cBanco;
switch (x) {
case "012":
text = "BBVA BANCOMER";
break;
case "014":
text = "SANTANDER";
break;
case "032":
text = "IXE";
break;
default:
text = "No value found";
}
document.getElementById("Banco").value = text;
document.getElementById("myBtn").disabled = false;
$('#form').submit(); //submit form if all validation succeeds
}
} else {
return false;
}
}
function someFunc() {
//myFunction2();
var x = document.getElementById("clabe2").value;
f2(x, '37137137137137137');
//return true;
}
function f2(a, b) {
var cad = Array.from(a, (v, i) => v * b[i] % 10).join('');
//se suman todos los digitos del array
var value = cad,
sum = value
.toString()
.split('')
.map(Number)
.reduce(function(a, b) {
return a + b;
}, 0);
//separate last digit from result
var number = sum;
// convert number to a string, then extract the first digit
var one = String(number).charAt(1);
// convert the first digit back to an integer
var one_as_number = Number(one);
var digito_control = (10 - one_as_number);
if (digito_control === 10) {
digito_control = 0;
var dg = digito_control;
} else {
dg = digito_control;
}
var z = document.getElementById("control2").value;
if (dg != z) {
alert("checkig digit is not equal");
return false;
} else if (dg == z) {
alert("checkig digit is equal");
return true;
}
}
<form action="<?php echo base_url();?>index.php/Datos/agregar" method="post" id="form"> <!-- I included an id to form -->
Enter CLABE account:
<input name="clabe" id="clabe" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control" id="control" maxlength="1" size="2" required> Again:
<input name="clabe2" id="clabe2" type="text" pattern=".{17,17}" maxlength="17" required title="17 números exactamente" />
<input type="text" name="control2" id="control2" maxlength="1" size="2" required>
<hr> Bank: <input type="text" name="Banco" id="Banco" readonly required onmousemove="comparaclabe();">
<hr> Observations: <input type="text" name="Observaciones" id="Observaciones" required>
<hr>
<input type="button" id="myBtn" value="Guardar Cambios" onclick="return compareclabe();"><span id="msg"></span>
<hr>
<input type="hidden" id="cve_banco" name="cve_banco">
</form>
<hr>
But there are many validation plugins where you can easily implement. No need to code from begining. Refer this for an example -> https://jqueryvalidation.org/

You can disable the button by default, and add event listeners to all the inputs in your form. But be weary of other ways to submit the form, like the enter key. I would add an onsubmit function just to prevent all ways the event can happen when you don't want it to.
const form = document.querySelector('form')
const inputs = [...form.querySelectorAll('input')] // convert node list to array
const isValid = () => {
let valid = false
disableButton()
// handle your conditions here
if (valid) enableButton()
return valid;
}
inputs.forEach( input => input.addEventListener('input', isValid))
form.onsubmit = event => if (!isValid()) event.preventDefault()
Or ES5 if you prefer:
var form = document.querySelector('form');
var inputNodes = form.querySelectorAll('input');
var inputs = Array.prototype.call.slice(inputNodes); // convert node list to array
var isValid = function() {
var valid = false;
disableButton();
// handle your conditions here
if (valid) enableButton();
return valid
}
inputs.forEach( function(input) {
input.addEventListener('input', isValid);
});
form.onsubmit = function(event) {
if (!isValid()) event.preventDefault();
};
It's also worth noting that HTML5 has a lot of built-in validation you can take advantage of.

Related

textarea isn't reading input that I have made [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
So no matter what I change if I input anything in the textarea it is not reading anything from the form.
I needed it to be able to have input and not just change the default message of the textarea. If there is any other error in my code please help me by correcting me. And this is only purely html and javascript.
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").innerHTML;
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").innerHTML = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">
Try value instead of innerHTML for textarea control.
function findReplace() {
var str = document.getElementById("message").value; //use value here
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res; //use value here
}
Note: There is no element with id demo in the HTML which is used in your JS.
Demo:
function manage(txt) {
var input = document.getElementById('replace');
if (txt.value != '') {
input.disabled = false;
}
else {
input.disabled = true;
}
}
function findReplace() {
var str = document.getElementById("message").value;
console.log(str)
var find = document.getElementById("find").value;
var replace = document.getElementById("replace").value;
var res = str.replaceAll(find, replace);
document.getElementById("message").value = res;
}
function Counter(str) {
var str = document.getElementById("message").innerHTML;
var msg = str.split(" ");
var element = document.getElementById("replace").value;
var count = 0;
for ( var i = 0; i < msg.length; i++)
{
if (element == msg[i])
{
count++;
i++;
} else
{
i++;
}
//document.getElementById("demo").innerHTML = "Number of replacement: " + count;
}
}
<!-- Message -->
<label for="message">Message: </label><br>
<textarea required type = "text" id="message" name = "message" rows="3" cols="20" method = "post">Hello testing</textarea><br>
<!-- Finding box -->
<label for="find">Find: </label><br>
<input type="text" id="find" name="find" onkeyup = "manage(this)"><br>
<!-- Replace box -->
<label for="replace">Replace with: </label><br>
<input disabled type="text" id="replace" name="replace">
<!--Submit button -->
<input type="button" value="find and replace" onclick ="findReplace(); Counter();">

Javascript loop array for form validation

I have a table form with some rows, that are controlled by user. Meaning they can add as more as they want. Let's pretend user requested 5 rows and i need to check if they all have values.
function validateForm() {
var lastRowInserted = $("#packageAdd tr:last input").attr("name"); // gives me "packageItemName5"
var lastCharRow = lastRowInserted.substr(lastRowInserted.length - 1); // gives me 5
var i;
for (i = 1; i <= lastCharRow; i++) {
var nameValidate[] = document.forms["packageForm"]["packageItemName"].value;
if(nameValidate[i].length<1){
alert('Please fill: '+nameValidate[i]);
return false;
}
}
}
How can i receive packageItemName1 to 5 values in a loop so then I can use to validate them. Want the loop to process this code
var nameValidate[] = document.forms["packageForm"]["packageItemName1"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName2"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName3"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName4"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName5"].value;
Like this
const validatePackageItems = () => {
const nameValidate = $("form[name=packageForm] input[name^=packageItemName]"); // all fields with name starting with packageItemName
const vals = nameValidate.map(function() { return this.value }).get(); // all values
const filled = vals.filter(val => val.trim() !== ""); // all values not empty
console.log("Filled", filled, "= ", filled.length, "filled of", vals.length)
return filled.length === vals.length
};
$("[name=packageForm]").on("submit",(e) => {
if (!validatePackageItems()) {
alert("not valid");
e.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="packageForm">
<input type="text" name="packageItemName1" value="one" /><br/>
<input type="text" name="packageItemName2" value="two" /><br/>
<input type="text" name="packageItemName3" value="" /><br/>
<input type="text" name="packageItemName4" value="four" /><br/>
<input type="submit">
</form>
You can use string interpolation to get the key dynamically:
for (let i = 1; i < 6; i++) {
const currentValue = document.forms.packageForm[`packageItemName${i}`]
console.log('current value:', currentValue)
}

Uncaught TypeError: Cannot read property 'checked' of undefined, Checkboxes

I want to validate my checkboxes to make sure that the user checked at least one, however I keep getting this error:
Uncaught TypeError: Cannot read property 'checked' of undefined.
Here is part of the HTML:
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required): <input type="text" name="userName" id="userName" required=""><br> E-Mail (Required): <input type="text" name="mail" id="mail" required=""><br> Phone (Required): <input type="text" name="phone" id="phone" required="" onchange="validNumber()"><br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other <br>
<textarea></textarea><br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and part of the JavaScript for the checkboxes:
function validChoice()
{
var bookChoice = document.userSurvey.books.value;
var x= "";
for (i=0;i< 4;i++)
{
if (document.userSurvey['bookChoice'+i].checked)
{
bookChoice = document.userSurvey['bookChoice'+i].value;
x = x +"\n"+ bookChoice;
}
}
if (bookChoice == "")
{
window.alert("You must select at least one book category.");
return false;
}
else
{
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
return true;
}
}
I am currently learning in JavaScript therefore I would prefer help in JavaScript only.
Full Code on JSFiddle:
https://jsfiddle.net/7qh5segc/
You missed some tag names and missspell them in js function:
<h1>User Survey</h1>
<h2><strong>User Information</strong></h2>
<p>Please enter your details below</p>
<br>
<form name="userSurvey" onsubmit="return validAll()" action="mailto:suvery#worldbook.com" method="post">
Name (Required):
<input type="text" name="userName" id="userName" required="">
<br> E-Mail (Required):
<input type="text" name="email" id="email" required="">
<br> Phone (Required):
<input type="text" name="phone" id="phone" required="" onchange="validNumber()">
<br>
<br>
<p>Please choose your favourite types of books.(check all that apply)</p>
<input type="checkbox" name="books" value="Science Fiction">Science Fiction
<input type="checkbox" name="books" value="Travel Guide">Travel Guide
<input type="checkbox" name="books" value="Short Story Collection">Short Story Collection
<input type="checkbox" name="books" value="Other">Other
<br>
<textarea></textarea>
<br>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
and js code goes like this:
function validName() {
var name = document.userSurvey.userName.value;
if (!/^[a-zA-Z]*$/g.test(name)) {
alert("Please enter letters a - z only");
document.userSurvey.userName.focus();
return false;
} else {
return true;
}
}
function validNumber() {
var theNumbersOnly = "";
var theChar = "";
var theInput = document.userSurvey.phone.value;
for (i = 0; i < theInput.length; i++) {
theChar = theInput.substring(i, i + 1);
if (theChar >= "0" && theChar <= "9") {
theNumbersOnly = "" + theNumbersOnly + theChar;
}
}
if (theNumbersOnly.length < 10) {
alert("You must enter 10 numbers.");
document.userSurvey.phone.focus();
} else {
var areacode = theNumbersOnly.substring(0, 3);
var exchange = theNumbersOnly.substring(3, 6);
var extension = theNumbersOnly.substring(6, 10);
var newNumber = "(" + areacode + ") ";
newNumber += exchange + "-" + extension;
document.userSurvey.phone.value = newNumber;
return true;
}
}
function validEmail() {
var email = document.userSurvey.email.value;
var atLoc = email.indexOf("#", 1);
var dotLoc = email.indexOf(".", atLoc + 2);
var len = email.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc + 2) {
return true;
} else {
alert("Please enter your e-mail address properly.");
return false;
}
}
function validChoice() {
//var bookChoice = document.userSurvey.books.value;
var bookChoice;
var x = "";
for (var i = 0; i < 4; i++) {
if (document.userSurvey.books[i].checked) {
console.log(document.userSurvey);
bookChoice = document.userSurvey.books[i].value;
x = x + "\n" + bookChoice;
}
}
if (bookChoice == "") {
window.alert("You must select at least one book category.");
return false;
} else {
var userName = document.userSurvey.userName.value;
var eMail = document.userSurvey.email.value;
var phoneNo = document.userSurvey.phone.value;
console.log(userName);
console.log(eMail);
console.log(phoneNo);
return true;
}
}
function validAll() {
if ((validName() == true) && (validEmail() == true) && (validNumber() == true) && (validChoice() == true)) {
return true;
} else {
return false;
}
}
You missed email tag name too. regards
You can fix the checkbox issue using the following code. A sensible way to get all the checkboxes in this case is using their shared "name" attribute. There are other ways if your structure was different - e.g. using a CSS class, or adding some other custom attribute to the elements.
function validChoice() {
var bookChoices = "";
var checkboxes = document.getElementsByName("books"); //get all elements named "books" into an array
for (i = 0; i < checkboxes.length; i++) { //loop the array
if (checkboxes[i].checked) { //if the array item at this index is checked, then add it to the list
bookChoices += "\n" + checkboxes[i].value;
}
}
if (bookChoices == "") {
window.alert("You must select at least one book category.");
return false;
} else {
alert(bookChoices); //just for testing
return true;
}
}
See https://jsfiddle.net/7qh5segc/3/ for a demo using the changed validChoice() function.

GPA Calculator, how to make letter inputs into numbers

I am trying to make a simple GPA calculator. There are 4 forms and I'm trying to make it so a user enters 4 letters (A,B,C,D, or F) and have each of those numbers represent a value (A = 4.0, B=3.0 ect.) And basically just get the average of them all. Right now I just made it so it so it works if the user enters numbers, but now I want to change it so the user enters the letter grades and get the same gpa number. I have no idea how to do this. Please help thank you.
(This is my html)
<!DOCTYPE html>
<html>
<head>
<title>GPA Calculator</title>
<link type="text/css" rel="stylesheet" href="project6.css">
<script type="text/javascript" src="project6.js"></script>
</head>
<body>
<h1>Enter Your Grades Below</h1>
<form name="form" id="form">
<br>
<input type="text" class="textForm1" name="textForm1"></input><br>
<input type="text" class="textForm1" name="textForm2"></input><br>
<input type="text" class="textForm1" name="textForm3"></input><br>
<input type="text" class="textForm1" name="textForm4"></input><br>
<button type="button" onClick="getGrade()">Submit</button>
</form>
<div id="div">
</div>
</body>
</html>
(This is my javascript)
var getGrade = function() {
var inputOne = document.form.textForm1.value;
var inputTwo = document.form.textForm2.value;
var inputThree = document.form.textForm3.value;
var inputFour = document.form.textForm4.value;
document.getElementById("div").innerHTML = (Number(inputOne) + Number(inputTwo) + Number(inputThree) + Number(inputFour))/4;
}
The basic idea is you want to create a mapping between letters and numbers.
The simplest possible way to do this would be a series of if statements.
var input = document.querySelector('input');
input.addEventListener('input', function() {
var inputValue = input.value;
if (inputValue === 'A') {
inputValue = 4.0;
} else if (inputValue === 'B') {
inputValue = 3.0;
} else if (inputValue === 'C') {
inputValue = 2.0;
} else if (inputValue === 'D') {
inputValue = 1.0;
} else {
inputValue = 0.0;
}
console.log(inputValue);
});
1: <input type="text" />
but this gets very tedious, especially if you have multiple inputs. Another option would be to move this functionality into a function then use that function multiple times.
function letterToNumber(letter) {
if (letter === 'A') {
return 4.0;
} else if (letter === 'B') {
return 3.0;
} else if (letter === 'C') {
return 2.0;
} else if (letter === 'D') {
return 1.0;
} else {
return 0.0;
}
}
document.querySelector('button').addEventListener('click', function() {
var input1 = document.getElementById('input1').value;
var input2 = document.getElementById('input2').value;
var input3 = document.getElementById('input3').value;
var input4 = document.getElementById('input4').value;
input1 = letterToNumber(input1);
input2 = letterToNumber(input2);
input3 = letterToNumber(input3);
input4 = letterToNumber(input4);
console.log(input1, input2, input3, input4);
});
1: <input id="input1" type="text" /><br />
2: <input id="input2" type="text" /><br />
3: <input id="input3" type="text" /><br />
4: <input id="input4" type="text" /><br />
<button>Calculate</button>
This works fine. You could simplify it even further by creating an object where the keys match the letter and the value matches the actual number value.
var letterToNumber = {
A: 4.0,
B: 3.0,
C: 2.0,
D: 1.0
};
document.querySelector('button').addEventListener('click', function() {
var input1 = document.getElementById('input1').value;
var input2 = document.getElementById('input2').value;
var input3 = document.getElementById('input3').value;
var input4 = document.getElementById('input4').value;
input1 = letterToNumber[input1];
input2 = letterToNumber[input2];
input3 = letterToNumber[input3];
input4 = letterToNumber[input4];
console.log(input1, input2, input3, input4);
});
1: <input id="input1" type="text" /><br />
2: <input id="input2" type="text" /><br />
3: <input id="input3" type="text" /><br />
4: <input id="input4" type="text" /><br />
<button>Calculate</button>
No matter what approach you take, remember the basic principle: if I get some value X I want to get some value Y. These are just examples of how to map that idea.
There's also a JavaScript Map that will handle all the association for you.
MDN JavaScript Reference: Map
var vals = new Map();
vals.set("A", 4.0);
vals.set("B", 3.0);
vals.set("C", 2.0);
vals.set("D", 1.0);
vals.set("F", 0.0);
And to retrieve:
var grade = document.getElementById("myGrade");
var gradeVal = vals.get(grade);
Of course you would do the retrieval in a loop, getting the values for all the grades entered by a user and calculating the average. This is just a simple example of using a Map.
I would create another Javascript function that takes the input and calculates it, and then you can output from that function.
Inside the function, you can change the letters to numbers.
JavaScript
const calculateGrade = () => {
const grades = [inputOne, inputTwo, inputThree, inputFour]
let sum = 0
for (let i = 0; i < grades.length; i++) {
switch (grades[i]) {
case "A":
sum += 4.0
case "B":
sum += 3.0
case "C":
sum += 2.0
case "D":
sum += 1.0
}
}
return (sum / 4)
}
I read all the answers and all gave me different ideas of what to do, but in the end, I followed mostly what Mike C. did, but not exactly the same way. Here's what I ended up with that worked perfectly.
var gradeValues = {
"A": 4.0,
"B": 3.0,
"C": 2.0,
"D": 1.0,
"F": 0
};
var getGrade = function() {
input1 = document.form.input1.value;
input2 = document.form.input2.value;
input3 = document.form.input3.value;
input4 = document.form.input4.value;
document.getElementById("result").innerHTML = ((gradeValues[input1] + gradeValues[input2] + gradeValues[input3] + gradeValues[input4]) / 4) + " is your GPA";
};

JavaScript Calculating wrong

I am trying to perform calculation using JavaScript. When user enter less than 10 pages in input (#page) the cost is 1. if he adds more than 10, each page costs .10. there are 2 options for checkbox, if he clicks first checkbox 10 is added and second checkbox 15 is added.
This is working when it is done in sequential steps. (input then clicking checkbox).
Ex: Input is : 9 (total: 1)
click checkbox1 - duplicates (total : 11)
click checkbox1 - laser (total: 26)
Now if i change the Input to 11, then the total becomes 1.10 - even if both the checkboxes are checked.. (expected result should be - 26.10)
I am not sure how to do this...can anyone help me out
<html>
<head>
<title>Calculation</title>
<script>
function calculate() {
var pages=document.getElementById("page").value;
if(pages <=10) {
total.value=1;
}
if(pages >= 11) {
var extra_pages= pages - 10;
var new_total= extra_pages * .10;
var new_total1= 1 + new_total;
total.value= new_total1;
}
}
function checkbox1() {
if(document.getElementById("ckbox1").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 10;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox1").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 10;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
function checkbox2() {
if(document.getElementById("ckbox2").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 15;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox2").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 15;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
</script>
<body>
Enter a Number: <input type="text" id="page" value="1" oninput="calculate()">
<br>
<br><br><br><br>
duplicates <input type="checkbox" id="ckbox1" onclick="checkbox1()">
laser print: <input type="checkbox" id="ckbox2" onclick="checkbox2()"> <br><br>
Total: <input type="text" id="total">
</body>
</html>
You can use calculate for all changes instead of creating each one for each input, which makes the calculation complex.
// Get reference to inputs.
var page = document.getElementById("page");
var total = document.getElementById("total");
var dup = document.getElementById("ckbox1");
var laser = document.getElementById("ckbox2");
function calculate() {
// To Number
var pages = parseInt(page.value, 10);
var value = 0;
if (pages <= 10) {
value = 1;
} else {
var extra_pages = pages - 10;
var new_total = extra_pages * .10;
var new_total1 = 1 + new_total;
value = new_total1;
}
// Add 10 if dup is checked.
if (dup.checked) {
value += 10;
}
// Add 15 if laser is checked.
// These can be moved out like
// const laserVal = 15;
// value += laserVal if you don't want magic number here.
if (laser.checked) {
value += 15;
}
// Truncate float.
total.value = value.toFixed(1);
}
Enter a Number:
<input type="text" id="page" value="1" oninput="calculate()">
<br>
<br>
<br>
<br>
<br>
duplicates:<input type="checkbox" id="ckbox1" onclick="calculate()">
laser print:<input type="checkbox" id="ckbox2" onclick="calculate()">
<br>
<br>Total:
<input type="text" id="total">

Categories

Resources