GPA Calculator, how to make letter inputs into numbers - javascript

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";
};

Related

Generate user id using javascript and display it in textbox

So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.

Deactivate a button until all javascript conditions have been checked

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.

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">

Javascript won't calculate

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

How to store inputs from a textbox in array in Javascript

<!DOCTYPE html>
<html>
<head>
<form id="form1">
Beets:<input id="number1" type="integer" size = "5">
Artichokes: <input id="number2" type="integer" size = "5">
Carrots: <input id="number3" type="integer" size = "5">
</form>
<button id = "submitButton" onclick="RunApp()" > Submit</button>
<button id = "displayButton" onclick="getAllValues()" > Display</button>
<script>
var str = "";
function getAllValues() {
var input1, inputs;
input1 = document.getElementById("form1");
inputs = input1.elements["number1"].value;
for (i = 0; i < inputs.length; i++) {
str += inputs[i].value + " ";
}
alert(str);
}
function RunApp()
{
var beets, artichokes, carrots, input1, input2, input3;
// getting inputs into variables
input1 = document.getElementById("form1");
beets = input1.elements["number1"].value;
input2 = document.getElementById("form1");
artichokes = input1.elements["number2"].value;
input3 = document.getElementById("form1");
carrots = input1.elements["number3"].value;
if (beets == "" || carrots == "" || artichokes == "" || isNaN(beets) || isNaN(carrots) || isNaN(artichokes))
{
document.getElementById("demo").innerHTML+= "not valid" + "<br>";
document.getElementById("demo").innerHTML+= "--------------------------" + "<br>";
}
else
{
document.getElementById("demo").innerHTML+= "Beets = " + beets + "<br>"; document.getElementById("demo").innerHTML+= "Artichokes = " + artichokes + "<br>";
document.getElementById("demo").innerHTML+= "Carrots = " + carrots + "<br>";
}
}
</script>
<p id="demo"></p>
</head>
<body>
</body>
</html>
First, this is my first time learning JS.
So, I have a text-box, a submit button, and a display button. When I enter a number in the text-box, and click submit, it shows the number. I enter my second number and clicking the submit button shows me the second number. Then I click on the display button, it will shows the number 1 and number 2 in order. If I have more inputs in the text-box, the display button will show the entire list of all the inputs from the array.
Thank you!
Well, since it's your first time and you're learning I won't just give you the answer, but I'll point you in the right direction.
You want to attach a click event on the submit button to add the value to an array, and then print the array on click of the display button.
i think first you must google for this. I write something and you can improve this. I only want to give an example.
HTML:
<input type="text" id="inputbox">
<br/>
<button type="button" id="submit">Submit</button>
<button type="button" id="display">Display</button>
<br/>
<div id="screen"></div>
JS:
var inputArray = [];
var input = document.getElementById('inputbox');
var screen = document.getElementById('screen');
document.getElementById('submit').onclick = function () {
inputArray.push(input.value);
screen.innerHTML = input.value;
};
document.getElementById('display').onclick = function () {
screen.innerHTML = inputArray
};
http://jsfiddle.net/y9wL27y0/

Categories

Resources