Having trouble displaying total cost - javascript

I am struggling to calculate the totalPrice and finalPrice, I've been working on this for hours. I tried everything, am I supposed to put the if and else statements in the script? Tried everything, doesn't work, my clear button doesn't clear either. Thanks for your help!!!
<html>
<head>
<meta charset = "UTF-8">
<title> World Travel </title>
<style>
body {background-color: black; font-family: optima;
color: white; text-align: left}
p { font-size: 20px}
button {font-size: 20px; background-color: white}
input { font-size: 20px}
</style>
</head>
<body>
<script>
var hotelNights= 0;
var travelPrice = 0;
var totalPrice = 0;
var finalPrice = 0;
</script>
<h1> World Travel </h1>
<h2> Price Processing </h2>
<p> Select Destination:
<input type = "radio" id = "a" name = "destination" size = "3"
onclick = /> Europe
<input type= "radio" id = "b" name= "destination" size = "3"
onclick = "destination == 'a';" /> Africa
</p>
<p> Select Air Travel Option:
<input type = "radio" id = "o" name = "airTravel" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 500; }
else {
totalPrice += 700; }
" /> One Way
<input type= "radio" id = "x" name = "airTravel" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 900; }
else {
totalPrice += 1300; }
" /> Round Trip
</p>
<p> Enter number of Hotel nights:
<input type = "text" id = "hotelNights" value = ""
onchange = "
if (destination == "e") {
totalPrice += 300*document.getElementaryById("hotelNights").value; }
else {
totalPrice += 200*document.getElementaryById("hotelNights").value; } " />
</p>
<p> Select Tour type:
<input type = "radio" id = "g" name = "tourPrice" size = "3"
onclick = "
if (desination == "e") {
totalPrice += 1500; }
else {
totalPrice + = 1300; } "/> Grand Package
<input type = "radio" id = "z" name = "tourPrice" size = "3"
onclick = "
if (destination == "e") {
totalPrice += 800; }
else {
totalPrice += 500; } " /> Basic Package
</p>
<p>
<button onclick="
finalPrice= (totalPrice*1.15);
totalPriceTextBox.value = '$' + totalPrice.toFixed(2);
finalPriceTextBox.value = '$' + finalPrice.toFixed(2);
"> Process </button>
</p>
<p> Total Price: $
<input type = "text" id = "totalPriceTextBox" value = "" readonly />
</p>
<p> Final Price (includes 15% surcharge): $
<input type = "text" id = "finalPriceTextBox" value = "" readonly />
</p>
<p>
<button onclick= "
a.checked = false;
hotelNights = '';
o.checked = false;
g.checked = false;
totalPriceTextBox.value = '';
finalPriceTextBox.value = '';
id_of_radio_button.checked = false;
id_of_text_box = '';
"> Clear </button>
</p>
<body>
</html>
......................................................................................................................................................................................................................................................................................................................................................................................................

You can't use double quotes in an inline onclick handler:
onclick = "
if (destination == "e") { // Can't use double quotes here because you're already inside a set of double quotes!
totalPrice += 900; }
else {
totalPrice += 1300; }
" />
You also need to declare and initialize destination.
Also, this onclick looks wrong:
<input type = "radio" id = "a" name = "destination" size = "3"
onclick = /> Europe

Related

My function in html isn't working properly

I made a function to calculate average and tried to use this function in each section. But the calculation isn't working properly. If you see the code below, the handleCalculateAverageButtonClick('Question1') function works in first section (section class = "Question1") but the handleCalculateAverageButtonClick('Question2') function's calculation is wrong in the second section (second class="Question2"). Is there something to modify in my code?
html code
<section class = "Question1">
how many times do you want to buy on scale?
<input type = "number" style = "height : 20px ; width: 50px; " class = "scale-count" />
<button type = "button" onclick = "handleNextButtonClick('Question1')" style = "padding
: 4px 19px;">
Next
</button>
<div class = "form-output"> </div>
<br>
<button class = "button button1" onclick =
"handleCalculateAverageButtonClick('Question1')">
CalculateAverage
</button> :
<span class= "average1"></span>
</section>
<section class = "Question2">
How many times do you want to sell on scale?
<input type = "number" style ="height : 20px; width: 50px;" class = "scale-count" />
<button type = "button" onclick = "handleNextButtonClick('Question2')" style =
"padding:4px 19px;">
Next
</button>
<div class = "form-output"></div>
<br>
<button class = "button button1" onclick =
"handleCalculateAverageButtonClick('Question2')">
CalculateAverage
</button> :
<span class = "average1"></span>
</section>
javascript code
function getNumberOfScales(){
const temp = parseInt(document.querySelector("." + parent + " .scale-count").value);
const numberOfScales = isNaN(temp) || temp<0 ? 0 : temp;
return numberOfScales;
}
function rowGenerator(index){
return `
<div class = "row" data-index = "${index}">
&nbsp &nbsp Price ${index} : &nbsp <input class = "price" style = "height : 30px ; width:
50px;"
data-index = "${index}" type = "number" /> &nbsp Count : &nbsp
<input class = "count" style = "height : 30px ; width: 50px;" data-index = "${index}" type
= "number" />
</div> `;
}
function handleNextButtonClick(parent){
const numberOfScales = getNumberOfScales(parent);
const formOutput = document.querySelector("."+parent+" .form-output");
let stringBuffer = " ";
for (let index=1; index<= numberOfScales; index++){
stringBuffer += rowGenerator(index);
}
formOutput.innerHTML = stringBuffer;
}
function getAverage(parent){
let sum = 0 ;
let sum_count = 0;
const numberOfScales = getNumberOfScales(parent);
for (let index = 1; index <= numberOfScales; index++){
const row_price = document.querySelector(`input.price[data-index = '${index}']`).value ;
const row_count = document.querySelector(`input.count[data-index = '${index}']`).value ;
sum += row_price * row_count;
sum_count += parseInt(row_count);
}
console.table({
sum,
sum_count
})
if (sum_count ==0 ){
return 0;
} else{
return sum/sum_count ;
}
}
function handleCalculateAverageButtonClick(parent) {
const average = getAverage(parent);
const avg1 = document.querySelector("." + parent +" .average1");
avg1.innerHTML = average;
}

Input not being read by code in JavaScript

I'm having trouble with my JS form. So I'm creating a change calculator which takes in two input values - the price and cash. When I explicity put in the actual values inside JS code (like the ones I commented out after confirmValues()), it works just fine. But when I put it in the actual input box, it doesn't give work anymore. Is there something weird with my HTML or JS? Thanks!
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title> Change calculator</title>
</head>
<body>
<form>
How much does the item cost? <input type="number" id="price" name ="price"/>
<br/> <br/>
How much cash do you have? <input type="number" id="cash" name="cash"/><br/> <br/>
<input type="button" value="Enter" onclick="confirmItems();"/>
</form>
<p id="confirmation"></p>
<p id ="change"></p>
</body>
var itemCost = document.getElementById("price");
var cash = document.getElementById("cash");
var confirmation = document.getElementById("confirmation");
function confirmItems() {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.value + " and you have $" + cash.value + " to pay for it.";
createConfirmationBtn();
}
function createConfirmationBtn() {
let confirmationBtn = document.createElement("BUTTON");
const confirmationBtnText = document.createTextNode("Confirm");
confirmationBtn.appendChild(confirmationBtnText);
confirmation.appendChild(confirmationBtn);
confirmationBtn.onclick = function() {
confirmValues();
}
}
let changeEl = document.getElementById("change");
function confirmValues() {
if (parseFloat(cash.value) < parseFloat(itemCost.value)) {
changeEl.innerHTML = "Not enough cash";
} else if (parseFloat(cash.value) == parseFloat(itemCost.value)) {
changeEl.innerHTML = "Your change is $0.";
} else {
calculateChange();
}
}
// cash.value = 500;
// itemCost.value = 33.44;
let remainder = parseFloat(cash.value) - parseFloat(itemCost.value);
let finalOutput = new Array();
function calculateChange() {
while (remainder > 0) {
if (remainder >= 100) {
findChange(100.00);
} else if (remainder >= 50.00) {
findChange(50.00);
} else if (remainder >= 20.00) {
findChange(20.00);
} else if (remainder >= 10.00) {
findChange(10.00);
} else if(remainder >= 5.00) {
findChange(5.00);
} else if (remainder >= 1.00) {
findChange(1.00);
} else if (remainder >= 0.25) {
findChange(0.25);
} else if (remainder >= 0.10) {
findChange(0.10);
} else if (remainder >= 0.05) {
findChange(0.05);
} else {
findChange(0.01);
}
}
changeEl.innerHTML = finalOutput;
}
function findChange(value) {
//Step 1. Get number of dollar for each type of dollar
let dValue = parseInt(remainder / value);
// Step 2. Storing numDValue in an array
finalOutput.push("[$" + value + " x" + dValue+"]");
remainder = parseFloat(remainder - (value * dValue));
remainder = parseFloat(remainder.toFixed(2));
}
You need to have the vars inside the functions that need them or they will not pick up what the user enters
You can show and hide the confirm button
DRY, Don't Repeat Yourself
function confirmValues() {
let itemCost = document.getElementById("price").value;
let cash = document.getElementById("cash").value;
const confirmation = document.getElementById("confirmation");
const changeEl = document.getElementById("change");
const confirm = document.getElementById("confirm");
cash = isNaN(cash) || cash === "" ? 0 : +cash; // test valid input
itemCost = isNaN(itemCost) || itemCost === "" ? 0 : +itemCost;
if (cash < itemCost) {
changeEl.innerHTML = "Not enough cash";
} else {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.toFixed(2) + " and you have $" + cash.toFixed(2) + " to pay for it.";
changeEl.innerHTML = "Your change is $" + (cash - itemCost).toFixed(2);
confirm.classList.remove("hide");
}
}
.hide {
display: none;
}
<title> Change calculator</title>
<form>
How much does the item cost? <input type="number" id="price" name="price" />
<br/> <br/> How much cash do you have? <input type="number" id="cash" name="cash" /><br/> <br/>
<input type="button" value="Enter" onclick="confirmValues();" />
<input type="button" id="confirm" class="hide" value="Confirm" onclick="alert('Confirmed!')" />
</form>
<p id="confirmation"></p>
<p id="change"></p>

Using <label> <input> <br> in for loop

I'd like to ask on how to add label, input, and br in for loop please. I'm trying to create an application to calculate score/GPA with for loop. Basically, if I enter 4 then 4 boxes of test scores will show up for me to enter (the default value is 150) - and the maximum I can go is 5.
I'm having problem putting label, input, and br in the for loop - the code is fine and it ran, but you obviously see that I'm not using label, input, and br tags.
How may I add these in please?
For example, if I enter 3 in the number of exams, then setupInputBox() will generate three label, three input and three br elements.
I attached my codes below.
Thank you so much!
// define a function so that in js code, $ can be used to replace document.getElementById
var $ = function(id) {
return document.getElementById(id);
};
var numInputs = 1; //default setting, showing one test score input box
//define setupInputBox function to add more test score inputs boxes
var setupInputBox = function() {
$('testInputs').innerHTML = "";
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
numInputs = $('numscores').value;
numInputs = parseInt(numInputs);
// convert inputs into integer numerical value
//step-1.1: Add a condition in if() statement
//if user input for number of test scores is valid and in the range 1 to 5
if (Number.isInteger(numInputs) && numInputs >= 1 && numInputs <= 5) {
var mainDiv = document.getElementById("testInputs");
for (var i = 0; i < numInputs; i++) {
//Step-1.2.1: create new <label>, <input>, and <br> elements (use createElement() method)
var lbl = document.createElement('label');
var inp = document.createElement("input");
var br = document.createElement("br");
//Step-1.2.2: create text content node for each new <label> element ( use createTextNode() method )
lbl.append(document.createTextNode("Test-" + (i + 1)));
//Step-1.3.1: add for attribute to each new <label> element ( use setAttribute() method)
lbl.setAttribute("for", "score" + (i + 1));
//Step-1.3.2: add id, type, and value attributes to new <input> elements ( use setAttribute() method)
inp.setAttribute("id", "score" + (i + 1));
inp.setAttribute("value", "150");
inp.setAttribute("type", "number");
//Step-1.4: append each new <label>, <input>, and <br> elements to the <div> element with id=”testInputs”.
mainDiv.append(lbl, inp, br);
}
}
};
//whenever user changes selection on number of test scores to consider, setupInputBox function will be executed again
$('numscores').oninput = setupInputBox;
//define processEntries function to get user inputted test scores, do input validation, and caculate total and average points and
//determine the final letter grade. Display all results on web page.
var processEntries = function() {
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
var score = []; //define an array to hold test scores
var message = ""; //define a variable for containing and displaying error message
var totalscore = 0,
avgScore, finalScore;
var isValid = true;
for (var i = 0; i < numInputs; i++) //
{
$("score" + (i + 1)).className = "";
//step 2.1: add js code to read in each user inputted test score(s) from input test score boxes on the web page.
var test = document.getElementById("score" + (i + 1));
var testScore = parseFloat(test.value);
//step 2.2: add js code to validate each test score to make sure all inputted test scores are numerical values
//between 0 and 150 (i.e., no less than 0 and no greater than 150 points).
if (!Number.isNaN(testScore) && testScore >= 0 && testScore <= 150) {
//if a test score is valid, add that test score to the score array.
score.push(testScore);
} else {
isValid = false;
//if a test score is invalid, generate error message, and add that error messge to message string.
message += "Test-" + (i + 1) + " score input is invalid. Should be a number between 0 and 150.\n"
test.setAttribute("class", "error");
}
}
console.log(score); //print out score array in console
console.log(message); //print out message string in console
if (isValid) {
//step2.3: add js so that when all inputted test scores are valid, compute total points, average points (with zero decimal place), and
//final letter grade, and display them in the input boxes in the <div> element with id=’result’ on the web page.
for (var j = 0; j < numInputs; j++) {
totalscore += score[j];
}
totalscore = totalscore.toFixed(1);
avgScore = totalscore / numInputs;
avgScore = avgScore.toFixed(1);
var scoreTotal = document.getElementById('scoreTotal');
scoreTotal.value = totalscore.toString();
var scoreAvg = document.getElementById('scoreAvg');
scoreAvg.value = avgScore.toString();
avgScore = parseFloat(avgScore);
if (avgScore <= 150 && avgScore >= 120)
finalScore = "A";
else if (avgScore < 120 && avgScore >= 100)
finalScore = "B";
else if (avgScore < 100 && avgScore >= 80)
finalScore = "C";
else if (avgScore < 80 && avgScore >= 60)
finalScore = "D";
else if (avgScore < 60)
finalScore = "F";
var scoreFinal = document.getElementById("scoreFinal")
scoreFinal.value = finalScore
} else {
//If not all inputted test scores are valid, then create an alert box to display an error message
alert(message);
}
}; //end of processEntries function
//each time when calculate button is clicked, inputted test scores will be evaluated and
$("calculate").onclick = function() {
if (numInputs > 0 && numInputs < 6)
processEntries();
};
$("numscores").focus();
#import url(http://fonts.googleapis.com/css?family=Wellfleet);
body {
font-family: 'Wellfleet', Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 60%;
min-width: 600px;
border: 3px solid blue;
padding: 0 1em .5em;
}
h1 {
color: blue;
margin: .5em 0;
}
#teacher {
float: right;
margin: 0px 30px 0px 0px;
}
label {
float: left;
width: 10em;
text-align: right;
margin-bottom: .5em;
}
input {
width: 5em;
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: yellow;
}
#s1 {
display: inline-block;
}
#s1 input {
vertical-align: center;
float: left;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Score App</title>
<link rel="stylesheet" href="score.css">
</head>
<body>
<main>
<h2>The Test Scores App</h2>
<img src="teacher.png" id="teacher" alt="teacher" width="177" height="277">
<div id="s1">
<label for="numscores">How many tests you want to consider?</label>
<input type='number' id='numscores' min='1' max='10' value='1'>
</div>
<div id="testInputs">
<label for="score1">Test-1:</label>
<input type='number' id='score1' value='150' /><br>
</div>
<div id='result'>
<label for="scoreTotal">Total Points:</label>
<input type="number" id="scoreTotal" disabled><br>
<label for="scoreAvg">Avg Grade:</label>
<input type="number" id="scoreAvg" disabled><br>
<label for="scoreFinal">Final Letter Grade:</label>
<input type="text" id="scoreFinal" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
</div>
</main>
<script src="testScoreV2.js">
</script>
</body>
</html>
Use a template literal and you can make this a lot simpler
// define a function so that in js code, $ can be used to replace document.getElementById
var $ = function(id) {
return document.getElementById(id);
};
var numInputs = 1; //default setting, showing one test score input box
//define setupInputBox function to add more test score inputs boxes
var setupInputBox = function() {
$('testInputs').innerHTML = "";
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
//string to hold our new html
let newHTML = "";
numInputs = $('numscores').value;
numInputs = parseInt(numInputs);
// convert inputs into integer numerical value
//step-1.1: Add a condition in if() statement
//if user input for number of test scores is valid and in the range 1 to 5
if (Number.isInteger(numInputs) && numInputs >= 1 && numInputs <= 5) {
var mainDiv = document.getElementById("testInputs");
for (var i = 0; i < numInputs; i++) {
//Create new html using template literal
newHTML += `<label for='score${i+1}'>Test - ${i+1}</label><input type='number' value='150' id='score${i+1}'><br>`;
}
//Update the div
mainDiv.innerHTML += newHTML;
}
};
//whenever user changes selection on number of test scores to consider, setupInputBox function will be executed again
$('numscores').oninput = setupInputBox;
//define processEntries function to get user inputted test scores, do input validation, and caculate total and average points and
//determine the final letter grade. Display all results on web page.
var processEntries = function() {
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
var score = []; //define an array to hold test scores
var message = ""; //define a variable for containing and displaying error message
var totalscore = 0,
avgScore, finalScore;
var isValid = true;
for (var i = 0; i < numInputs; i++) //
{
$("score" + (i + 1)).className = "";
//step 2.1: add js code to read in each user inputted test score(s) from input test score boxes on the web page.
var test = document.getElementById("score" + (i + 1));
var testScore = parseFloat(test.value);
//step 2.2: add js code to validate each test score to make sure all inputted test scores are numerical values
//between 0 and 150 (i.e., no less than 0 and no greater than 150 points).
if (!Number.isNaN(testScore) && testScore >= 0 && testScore <= 150) {
//if a test score is valid, add that test score to the score array.
score.push(testScore);
} else {
isValid = false;
//if a test score is invalid, generate error message, and add that error messge to message string.
message += "Test-" + (i + 1) + " score input is invalid. Should be a number between 0 and 150.\n"
test.setAttribute("class", "error");
}
}
console.log(score); //print out score array in console
console.log(message); //print out message string in console
if (isValid) {
//step2.3: add js so that when all inputted test scores are valid, compute total points, average points (with zero decimal place), and
//final letter grade, and display them in the input boxes in the <div> element with id=’result’ on the web page.
for (var j = 0; j < numInputs; j++) {
totalscore += score[j];
}
totalscore = totalscore.toFixed(1);
avgScore = totalscore / numInputs;
avgScore = avgScore.toFixed(1);
var scoreTotal = document.getElementById('scoreTotal');
scoreTotal.value = totalscore.toString();
var scoreAvg = document.getElementById('scoreAvg');
scoreAvg.value = avgScore.toString();
avgScore = parseFloat(avgScore);
if (avgScore <= 150 && avgScore >= 120)
finalScore = "A";
else if (avgScore < 120 && avgScore >= 100)
finalScore = "B";
else if (avgScore < 100 && avgScore >= 80)
finalScore = "C";
else if (avgScore < 80 && avgScore >= 60)
finalScore = "D";
else if (avgScore < 60)
finalScore = "F";
var scoreFinal = document.getElementById("scoreFinal")
scoreFinal.value = finalScore
} else {
//If not all inputted test scores are valid, then create an alert box to display an error message
alert(message);
}
}; //end of processEntries function
//each time when calculate button is clicked, inputted test scores will be evaluated and
$("calculate").onclick = function() {
if (numInputs > 0 && numInputs < 6)
processEntries();
};
$("numscores").focus();
#import url(http://fonts.googleapis.com/css?family=Wellfleet);
body {
font-family: 'Wellfleet', Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 60%;
min-width: 600px;
border: 3px solid blue;
padding: 0 1em .5em;
}
h1 {
color: blue;
margin: .5em 0;
}
#teacher {
float: right;
margin: 0px 30px 0px 0px;
}
label {
float: left;
width: 10em;
text-align: right;
margin-bottom: .5em;
}
input {
width: 5em;
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: yellow;
}
#s1 {
display: inline-block;
}
#s1 input {
vertical-align: center;
float: left;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Score App</title>
<link rel="stylesheet" href="score.css">
</head>
<body>
<main>
<h2>The Test Scores App</h2>
<img src="teacher.png" id="teacher" alt="teacher" width="177" height="277">
<div id="s1">
<label for="numscores">How many tests you want to consider?</label>
<input type='number' id='numscores' min='1' max='10' value='1'>
</div>
<div id="testInputs">
<label for="score1">Test-1:</label>
<input type='number' id='score1' value='150' /><br>
</div>
<div id='result'>
<label for="scoreTotal">Total Points:</label>
<input type="number" id="scoreTotal" disabled><br>
<label for="scoreAvg">Avg Grade:</label>
<input type="number" id="scoreAvg" disabled><br>
<label for="scoreFinal">Final Letter Grade:</label>
<input type="text" id="scoreFinal" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
</div>
</main>
<script src="testScoreV2.js">
</script>
</body>
</html>

Unable to display text box results in div

I want to display all the resulting expressions under the Result and Entered button every time I hit "=". But I am stuck trying to figure it out. This is what I have so far. Any help would be much appreciated. Thank you.
<!DOCTYPE html>
<html>
<body>
<head>
</head>
<script>
//Fucntion to bring operation to the operators
function calculation()
{
var x = parseInt(document.getElementById("op1").value);
var y = parseInt(document.getElementById("op2").value);
var z = document.getElementById("operator").value;
var result;
if (z == "+"){
result = x + y;
document.getElementById("result").value = +result;
}else if (z == "-"){
result = x - y;
document.getElementById("result").value = +result;
}else if (z == "*"){
result = x * y;
document.getElementById("result").value = +result;
}else if (z == "/"){
result = x / y;
document.getElementById("result").value = +result;
}
displayResults();
}
function displayResults()
{
var dispArr = ["document.getElementById('op1').value", "document.getElementById('operator').value", "document.getElementById('op2').value",
"=","document.getElementById('result').value"];
dispArr.toString();
document.getElementbyId("expressions").innerHTML = dispArr.join("");
}
//Function to display the operators
function displayOptr(i) {
var optrArr =["+","-","*","/"];
if (i==0){
document.getElementById("operator").value = "+";
} else if (i==1){
document.getElementById("operator").value = "-";
} else if (i==2){
document.getElementById("operator").value = "*";
} else if (i==3){
document.getElementById("operator").value = "/";
}
}
</script>
<div id="bodyDiv">
<h1> CALCULATOR </h1>
<hr/>
<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onClick = "displayOptr(0)">ADD</div>
<div id = "subtract" class = "blocks" onClick = "displayOptr(1)">SUBTRACT</div>
<div id = "multiply" class = "blocks" onClick = "displayOptr(2)">MULTIPLY</div>
<div id = "divide" class = "blocks" onClick = "displayOptr(3)">DIVIDE</div>
</div>
</div>
<div class="rightDiv">
<div id = "calcblock">
<input type ="text" size="3" id="op1"/>
<input type = "text" size="1" id = "operator">
<input type = "text" size="3" id="op2"/>
<input type = "button" value = "=" id="calculate" onClick = "calculation()"/>
<input type = "text" size="6" id = "result" />
</div>
</div>
<hr/>
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut"><br><br>
<div id = "expressions"></hr></div>
</div>
</div>
</div>
</body>
</html>
The values for dispArr are in quotes so they're treated as strings. Remove the quotes, then you are using document.getElementbyId instead of document.getElementById on line 39 (under dispArr.toString();)
<html>
<body>
<head>
</head>
<script>
//Fucntion to bring operation to the operators
function calculation()
{
var x = parseInt(document.getElementById("op1").value);
var y = parseInt(document.getElementById("op2").value);
var z = document.getElementById("operator").value;
var result;
if (z == "+"){
result = x + y;
document.getElementById("result").value = +result;
}else if (z == "-"){
result = x - y;
document.getElementById("result").value = +result;
}else if (z == "*"){
result = x * y;
document.getElementById("result").value = +result;
}else if (z == "/"){
result = x / y;
document.getElementById("result").value = +result;
}
displayResults();
}
function displayResults()
{
var dispArr = [document.getElementById('op1').value, document.getElementById('operator').value, document.getElementById('op2').value,
"=",document.getElementById('result').value];
dispArr.toString();
document.getElementById("expressions").innerHTML = dispArr.join("");
}
//Function to display the operators
function displayOptr(i) {
var optrArr =["+","-","*","/"];
if (i==0){
document.getElementById("operator").value = "+";
} else if (i==1){
document.getElementById("operator").value = "-";
} else if (i==2){
document.getElementById("operator").value = "*";
} else if (i==3){
document.getElementById("operator").value = "/";
}
}
</script>
<div id="bodyDiv">
<h1> CALCULATOR </h1>
<hr/>
<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onClick = "displayOptr(0)">ADD</div>
<div id = "subtract" class = "blocks" onClick = "displayOptr(1)">SUBTRACT</div>
<div id = "multiply" class = "blocks" onClick = "displayOptr(2)">MULTIPLY</div>
<div id = "divide" class = "blocks" onClick = "displayOptr(3)">DIVIDE</div>
</div>
</div>
<div class="rightDiv">
<div id = "calcblock">
<input type ="text" size="3" id="op1"/>
<input type = "text" size="1" id = "operator">
<input type = "text" size="3" id="op2"/>
<input type = "button" value = "=" id="calculate" onClick = "calculation()"/>
<input type = "text" size="6" id = "result" />
</div>
</div>
<hr/>
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut"><br><br>
<div id = "expressions"></hr></div>
</div>
</div>
</div>
</body>
</html>

Javascript: Taking values from a textbox and adding it to the divs

So I have been racking my brain on how to add the a different value from the text box to a different div. So div1 gets the first thing the user typed, div2 gets the second, div3 gets the third, and so on. Everytime a user presses the "Add" button whatever the user typed will be added to one of the Div's above it. Right now I have it to where by pressing "Add" the value of the textbox is put in the first div. How do I create a function that will allow the user to add values to other divs. I assume you need a for loop but I do not know how to tackle it.
Here is my code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<div id="colorme" style = "cursor:pointer" onClick= "highlightLink()"><p id = "doubleStuff" ondblclick = "dubleStuff()">check this out</p></div>
<div id="colorme2" style = "cursor:pointer" onClick= "highlightLink2()"><p id = "doubleStuff2" ondblclick = "dubleStuff2()">check this out</p></div>
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick = "workInfoAdd()">Add</button>
<script>
function highlightLink(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'red';
highL2.style.backgroundColor = 'transparent';
};
function highlightLink2(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'transparent';
highL2.style.backgroundColor = 'red';
};
function dubleStuff(){
var x = "You double clicked it";
document.getElementById('putstuff').innerHTML = x;
};
function dubleStuff2(){
var x = "different stuff";
document.getElementById('putstuff').innerHTML = x;
};
function workInfoAdd(){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {
z.value = "";
}
};
</script>
</body>
</html>
Would something like this work.
var i = document.getElementById('addingInfo');
for(i = 0; i < 4; i++){
document.getElementbyId('workInfo').value = i //or some other variable that specifies the "adding info"
Any assistance would be greatly appreciated. As stated above after everytime the user presses ADD, the value they put into the text box will be added to the subsequent div. First add goes to first div, second goes to second div and so on.
You should probably write something like this:
var divIndex = 0;
function workInfoAdd() {
var z = document.getElementById('workInfo');
var p = document.getElementById('addingInfo' + (divIndex || ''));
if (!p) {
return;
}
if (z.value === null || z.value === "") {
alert('please enter work info');
} else {
p.innerHTML = z.value;
z.value = "";
}
divIndex++;
};
<div id="workInfo1" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo"></p>
</div>
<div id="workInfo12" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo1"></p>
</div>
<div id="workInfo13" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo2"></p>
</div>
<div id="workInfo14" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo3"></p>
</div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type="button" name="addWorkInfo" id="addWorkInfo" onclick="workInfoAdd()">Add</button>
Additionally you can use document.querySelector() for more advanced matching of elements ex.
var p = document.querySelector('.workInfo' + divIndex + ' > p.addingInfo' + divIndex);
Try the below code but remember that this solution should be used if you are going to limit the number of div (i.e only 3 or 4 divs) because if you want unlimited divs you will have to program an if-else statement for each possible div:
// Declare variable
var x = 0;
function workInfoAdd(){
// Increment
x++
// Check increment value
if(x == 1){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else { z.value = "";}
}
// Check increment value
else if(x == 2){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo1').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
// Check increment value
else if(x == 3){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo2').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
}
https://jsfiddle.net/6byvuzxf/
I have created check points as mentioned in my comment before.
Hope this helps.
See if this is what you want. I have added a class for all the p tags which will contain the information after click.
Html
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick ="workInfoAdd()">Add</button>
javascript
function workInfoAdd()
{
var elements = document.getElementsByClassName('addingInfo');
for(i=0;i<elements.length;i++)
{
if(elements[i].innerHTML == "")
{
elements[i].innerHTML = document.getElementById('workInfo').value;
document.getElementById('workInfo').value = "";
return;
}
}
}
http://jsfiddle.net/okLme061/1/

Categories

Resources