can I update a javascript variable being displayed using innerhtml - javascript

I'm trying to build a basic budget calculator tool in javascript which displays a running total at the top of the page which updates when individual budget items are changed. To do this I'm using [document.getElementById("runningTotal").innerHTML += total_sp;]. This works fine for calculating the running total but every time I make a change the new total is appended to the old total, so the output on screen makes no sense. Can anyone tell me how I can do this so that the running total updates every time a change is made replacing the old total with the new total? I'm new to all this, so very grateful for any help you can offer. Cheers!
<script>
// defining pre-change spending levels
var research_sp = 217200
var wage_sp = 155000
var total_sp = wage_sp + research_sp
function changeresearchspending() {
var nameElement = document.getElementById("researchcalc");
//defining percentage change to research spending levels
var research_r = nameElement.value;
var research_ch = research_r * research_sp;
var research_sp_end = research_sp + research_ch;
total_sp = total_sp + research_ch
document.getElementById("researchChange").innerHTML += research_ch;
document.getElementById("endresearchTotal").innerHTML += research_sp_end;
document.getElementById("endTotalSpend1").innerHTML += total_sp;
document.getElementById("runningTotal").innerHTML += total_sp;
}
function changewagespending() {
var nameElement = document.getElementById("wagecalc");
//defining percentage change to wage spending levels
var wage_r = nameElement.value;
var wage_ch = wage_r * wage_sp;
var wage_sp_end = wage_sp + wage_ch;
total_sp = total_sp + wage_ch
document.getElementById("wageChange").innerHTML += wage_ch;
document.getElementById("endwageTotal").innerHTML += wage_sp_end;
document.getElementById("endTotalSpend2").innerHTML += total_sp;
document.getElementById("runningTotal").innerHTML += total_sp;
}
</script>
<div id="runningTotal">
SPENDING (RUNNING TOTAL) £
</div>
<br>
<div id="startresearchTotal">
Baseline research spending is: £
<script>document.write(research_sp)</script>
<br><br>
Baseline wage spending is: £
<script>document.write(wage_sp)</script>
<br><br>
Baseline total spending is: £
<script>document.write(total_sp)</script>
</div>
<br>
<input id="researchcalc" type="number">
<input type="button" value="change research spend" onClick="changeresearchspending()">
<div id="researchChange">
<br> Change in research spending is: £
</div>
<div id="endresearchTotal">
<br> New research spending is: £
</div>
<div id="endTotalSpend1">
<br> New total spending is: £
</div>
</div>
<br>
<input id="wagecalc" type="number">
<input type="button" value="change wage spend" onClick="changewagespending()">
<div id="wageChange">
<br> Change in wage spending is: £
</div>
<div id="endwageTotal">
<br> New wage spending is: £
</div>
<div id="endTotalSpend2">
<br> New total spending is: £
</div>

You can replace the += by =, like this:
document.getElementById("runningTotal").innerHTML = total_sp;

Related

How do I show the random item that was generated from a list?

Once the "randomSong" is generated, I want it to show a sentence below like the following:
Use the !code(my randomly generated code) command in our chat forums to redeem premium.
function findSong() {
var song = ["xikskx", "iwnujk", "ldilxb", "hgbhrw", "ijkczb"];
var random = Math.floor(Math.random() * (song.length - 1));
document.getElementById("randomSong").setAttribute("value", song[random]);
}
<div>
<button onclick="findSong();" type="randomSong">Generate Premium Code</button>
<input "RandomCode" id="randomSong">
</div>
You could add <p> element to your html code that would be used to display the newly generated text.
<div>
<button onclick="findSong();" type="randomSong">Generate Premium Code</button>
<input "RandomCode" id="randomSong">
<!-- new code -->
<p id="text"></p>
</div>
And then fill it on click like this.
function findSong() {
var song = ["xikskx", "iwnujk", "ldilxb", "hgbhrw", "ijkczb"];
var random = Math.floor(Math.random() * (song.length - 1));
document.getElementById("randomSong").setAttribute("value", song[random]);
// new code
var premium = document.getElementById('text');
premium.textContent = 'Use the code ' + song[random] + ' command in our chat forums to redeem premium.';
}
fiddle: https://jsfiddle.net/LLu75ksf/5/

Problems converting a NaN value in Javascript

I'd just started learning Javascript and one of my first projects is to build a site that gets values from an input box and use them to get the area of a circle but I keep getting NaN as a result
My code looks like this:
let circle = document.getElementById("rCircle");
let radius = circle.value;
const calcAreaCircle = (radius) => {
let circleResult = Math.PI * Math.pow(radius, 2);
circleArea.innerHTML = ("The area is: " + circleResult)
};
Additional info - I have already tried converting the NaN using parseInt as let radius = parseInt(circle.value). Also I keep getting NaN in the console unless the code is wrapped in a window.onload function.
Does anybody know what am I missing??
*Edit
This is part of my html
<div class="imageContainer">
<h4>Circles</h4>
<div class="Figures"><img src="assets/circle-shape-outline.png" alt="Circle image"></div>
<div class="text">
<p>Tell me the radius</p>
<input type="number" name="" value="" placeholder="Raduis" id="rCircle">
<button id="calcCircle">Get area</button>
</div>
<p id="circleArea"></p>
</div>
function check() {
let circle = document.getElementById("rCircle");
let circleArea = document.getElementById("circleArea");
let radius = circle.value;
let circleResult = Math.PI * Math.pow(parseInt(radius), 2);
circleArea.innerHTML = ("The area is: " + circleResult)
}
<div class="imageContainer">
<h4>Circles</h4>
<div class="Figures"><img src="assets/circle-shape-outline.png" alt="Circle image"></div>
<div class="text">
<p>Tell me the radius</p>
<input type="number" name="" value="" placeholder="Raduis" id="rCircle">
<button id="calcCircle" onclick="check()">Get area</button>
</div>
<p id="circleArea"></p>
</div>
Have you tried parseInt with second param "null"?
parseInt(circle.value, null);
I have tested your code that the input value can be get inside the function. I have modified the code and is working fine for me. You may also want to make use of number input type to avoid parsing. In case of string number, the javascript will automatically convert it into number. You can check that by removing parsing.
<!Doctype HTML>
<html>
<body>
Enter Value: <input type="number" id='rCircle'>&nbsp
<button onclick="calcAreaCircle()">Calculate</button>
<br/>
<br/>
<span id="circleArea"></span>
<script>
var calcAreaCircle = function(){
var circle = document.getElementById("rCircle"),
circleArea = document.getElementById("circleArea");
radius = parseInt(circle.value,10);
console.log(parseInt(circle.value,10));
console.log(typeof radius+": "+radius);
var circleResult = Math.PI * Math.pow(radius, 2);
circleArea.innerHTML = ("The area is: " + circleResult)
};
</script>
</body>
</html>
make sure, you get correct value from input with id="rCircle"
As you said that your code is working fine after wrapping in window.onload it means that in normal case DOM loading is not finished before you called document.getElementById("rCircle").
Important thing is that how you are binding your JS code. You can check the DOM loading part of your input box by this:-
if(document.getElementById("rCircle").length > 0)
{
// Your JS Code like as
// let circle = document.getElementById("rCircle");
// let radius = circle.value;
// etc
}
else
{
// DOM is not loaded , ouu need to wait for DOM loading completion
}
or you can call the function manually and in thac case your DOM will be finished with loading -
HTML Code
<div class="imageContainer">
<h4>Circles</h4>
<div class="Figures"><img src="assets/circle-shape-outline.png" alt="Circle image"></div>
<div class="text">
<p>Tell me the radius</p>
<input type="number" name="" value="" placeholder="Raduis" id="rCircle">
<button id="calcCircle" onClick="getArea()">Get area</button>
</div>
<p id="circleArea"></p>
</div>
JS Code
<script>
function getArea(){
var circle = document.getElementById("rCircle"),
circleArea = document.getElementById("circleArea");
radius = parseInt(circle.value);
var circleResult = Math.PI * Math.pow(radius, 2);
circleArea.innerHTML = ("The area is: " + circleResult)
};
</script>

Javascript Array and While Loops

I am very new to javascript and I am trying to list a certain number of job duties on a resume site (dictated by a user input). For example, I ask the user to input the number of job duties they want to see, and using an array and while loop I've been tasked with displaying that many job duties. However, when I click the button, noting is happening. I am not getting any web console errors at all. Here is what I have so far:
<div id="right">
<p> <b> Byrne Dairy</b><br/>
QA Lab Technician<br/>
September 2015 - March 2016<br/><br/><br/>
<button value="Click" onclick="listDuties()">Click</button> to see my top
<input type="text" id="byrne_duties" value="0"/> job duties here:<br/><br/><br/>
<p id="duties"></p>
<script type="text/javascript">
function listDuties() {
var byrneduties = [ "Gathering product samples from sanitized silo and tank ports on a timely schedule. <br/> ",
"Regularly use of Delta Testing Instruments to measure solids and fat contents of products. ",
"Performing the Gerber Method of testing on samples. ",
"Responsible for using the Standard Plate Count method of developing colonies of bacteria. ",
"Interpreting results of bacterial and coliform growth patterns in products. " ];
var x = byrneduties[0];
var text = "";
while (byrneduties[x]) {
text += byrneduties[x] + "<br>";
x++;
document.getElementById('duties').innerHTML = x;
}
}
</script>
</div>
I was told to try and subtract one from the user input, but I'm not sure how to do that. Any help would be great!
Oh, there're some errors in your code:
First of all, your while condition is not a boolean (true/false) but a value of a string array
The var x that you use as index in the loop, is initialized with the first element of string array, then incremented (string+1?!) and finally returned back into an html object (p)
Look the following reviewed code, where I made the above little changes:
function listDuties() {
var byrneduties = ["Gathering product samples from sanitized silo and tank ports on a timely schedule. <br/> ","Regularly use of Delta Testing Instruments to measure solids and fat contents of products. ","Performing the Gerber Method of testing on samples. ","Responsible for using the Standard Plate Count method of developing colonies of bacteria. ","Interpreting results of bacterial and coliform growth patterns in products. " ];
var n = document.getElementById('byrne_duties').value;
var x = 0;
var text = "";
while (x < n) {
text += byrneduties[x] + "<br>";
x++;
}
document.getElementById('duties').innerHTML = text;
}
<div id="right">
<p> <b> Byrne Dairy</b><br/>
QA Lab Technician<br/>
September 2015 - March 2016<br/><br/><br/>
<button value="Click" onclick="listDuties()">Click</button> to see my top
<input type="text" id="byrne_duties" value="0"/> job duties here:<br/><br/><br/>
<p id="duties"></p>
</div>
I hope it was clear, bye.
However, when I click the button, noting is happening. I am not
getting any web console errors at all.
Your current code is simply going to display only one duty since it is over-writing the same div again and again. It is not even taking input from the textbox into consideration.
try this
<div id="right">
<p> <b> Byrne Dairy</b><br/> QA Lab Technician<br/> September 2015 - March 2016<br/><br/><br/>
<button value="Click" onclick="listDuties()">Click</button> to see my top
<input type="text" id="byrne_duties" value="0" /> job duties here:<br/><br/><br/>
<p id="duties"></p>
<script type="text/javascript">
function listDuties() {
var byrneduties = ["Gathering product samples from sanitized silo and tank ports on a timely schedule. <br/> ",
"Regularly use of Delta Testing Instruments to measure solids and fat contents of products. ",
"Performing the Gerber Method of testing on samples. ",
"Responsible for using the Standard Plate Count method of developing colonies of bacteria. ",
"Interpreting results of bacterial and coliform growth patterns in products. "
];
var numberOfDuties = Number( document.getElementById( "byrne_duties" ).value );
if ( !isNaN( numberOfDuties ) && numberOfDuties > 0 )
{
document.getElementById('duties').innerHTML = byrneduties.slice(0, numberOfDuties).join("<br>");
}
}
</script>
</div>
Problem:
var x = byrneduties[0]; // here x is variable which refer to first byrneduties
var text = "";
while (byrneduties[x]) { // here x is index, I think you meant 'i'
text += byrneduties[x] + "<br>";
x++;
document.getElementById('duties').innerHTML = x;
No need to loop, just join array
document.getElementById('duties').innerHTML = byrneduties.join('<br/>');
You could iterate the array with a foreach, like in the following example:
<div id="right">
<p> <b> Byrne Dairy</b><br/>
QA Lab Technician<br/>
September 2015 - March 2016<br/><br/><br/>
<button value="Click" onclick="listDuties()">Click</button> to see my top
<input type="text" id="byrne_duties" value="0"/> job duties here:<br/><br/><br/>
<p id="duties"></p>
<script type="text/javascript">
function listDuties() {
var byrneduties = [ "Gathering product samples from sanitized silo and tank ports on a timely schedule. <br/> ",
"Regularly use of Delta Testing Instruments to measure solids and fat contents of products. ",
"Performing the Gerber Method of testing on samples. ",
"Responsible for using the Standard Plate Count method of developing colonies of bacteria. ",
"Interpreting results of bacterial and coliform growth patterns in products. " ];
var text = "";
byrneduties.forEach( (duty, i)=>{
if ( (i+1) > document.getElementById('byrne_duties').value ) {
return;
}
text += (i+1) + ") " + duty + "<br/>"
});
document.getElementById('duties').innerHTML = text;
}
</script>
</div>
function listDuties() {
var byrneduties = [ "Gathering product samples from sanitized silo and tank ports on a timely schedule. <br/> ",
"Regularly use of Delta Testing Instruments to measure solids and fat contents of products. ",
"Performing the Gerber Method of testing on samples. ",
"Responsible for using the Standard Plate Count method of developing colonies of bacteria. ",
"Interpreting results of bacterial and coliform growth patterns in products. " ];
var x = 0;
var text = "";
var input =document.getElementById('byrne_duties').value
while (x<byrneduties.length && x<input) {
text += byrneduties[x] + "<br>";
x++;
document.getElementById('duties').innerHTML = text;
}
}
<div id="right">
<p> <b> Byrne Dairy</b><br/>
QA Lab Technician<br/>
September 2015 - March 2016<br/><br/><br/>
<button value="Click" onclick="listDuties()">Click</button> to see my top
<input type="text" id="byrne_duties" value="0"/> job duties here:<br/><br/><br/>
<p id="duties"></p>
</div>
Try this
Here is your mistakes.
var x = byrneduties[0]; // x is "Gathering product samples from sanitized silo and tank ports on a timely schedule. <br/>"
var text = "";
while (byrneduties[x]) { // byrneduties["Gathering product samples from sanitized silo and tank ports on a timely schedule. <br/>"] returns undefined
text += byrneduties[x] + "<br>";
x++; // string increment probably returns NaN
document.getElementById('duties').innerHTML = x; //set inner html to NaN.
}
Rewrite it in next way
var x = 0;
var text = "";
while (byrneduties[x]) {
text += byrneduties[x] + '<br/>';
x++;
}
document.getElementById('duties').innerHTML = text ;
Or use array.join
var text = byrneduties.join('<br/>');
document.getElementById('duties').innerHTML = text;

Simple Math with JS

Hello I need a quick hand, I have this div below
<div class="price">$1500</div>
I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.
<span class="payment">Pay as low as $"result here" </span>
I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.
First get text of div var text = $('.price').text(); // "$1500"
Then parse it as integer var price = text.replace(/[^\d]/, ''); // "$1500" -> 1500
Finally place text to where it belongs: $('.payment').text('Pay as low as $'+(price / 2 / 6));
$(document).ready(function () {
var text = $('.price').text();
var price = text.replace(/[^\d]/, '');
$('.payment span').text(price / 12);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $<span></span> </span>
Here, this one is pure javascript, try not to overcomplicate things
<html>
<body>
<div id="num">1500$</div>
<div id="num2"></div>
<script>
var number = document.getElementById("num").innerHTML.replace("$", "");
number = number / (2 * 6);
document.getElementById("num2").innerHTML = "Pay as low as " + number + " here";
</script>
</body>
</html>
You can achieve this as below mentioned.
$(document).ready(function(){
var price = $(".price").text(),
price = price.replace('$', '');
finalPrice = (price/2).toFixed(2);
$(".final-price").text(finalPrice/6);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<br> <br>
<div class="payment">Pay as low as $<span class="final-price"></span> </div>
get the text() of the element.
replace the $ sign
And divide by (2*6)
Apply with some Math.abs function its will calculate the result
Then apply the span and append into your body
var a = Math.abs(parseInt($('.price').text().replace('$',''))/(2*6))
$('body').append('<span class="payment">Pay as low as $'+a+' </span>')
.payment{
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
Try this
var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
$( ".payment" ).html( "Pay as low as " + (price/12) );
Demo
var price = parseInt( $( ".price" ).html().replace(/\D/g, "") );
$( ".payment" ).html( "Pay as low as " + (price/12) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $"result here" </span>
What you should do:
Get the .price div's text.
convert it to an int.
Now you should divide it with (value/2)/6
Put the value in the desired target element.
var price = +$('.price').text().slice(1);
var pay = (price/2)/6
$('p').text("Pay as low as $"+pay);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<p></p>
hope it help.
/*define a function to Deleting all characters other than numbers. in element*/
function checkIsInteger(sTr){
var newstr = "";
if(typeof sTr !== "undefine" && sTr!=""){
var indexInt = ['0','1','2','3','4','5','6','7','8','9'];
for(var i=0;i<sTr.length;i++){
var cek = sTr.substr(i,1)
if(indexInt.indexOf(cek)>=0){
newstr += sTr.substr(i,1);
}
}
}
return newstr;
}
$("#res").html((parseInt(checkIsInteger($("#price").html()))/2)/6);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="price" id="price">$1500</div>
<label class="payment" id="pym">Pay as low as $<span id="res">result</span> here </label>

Adding and subtracting using dynamic variable names in JQuery/Javascript

I am working on developing an inventory checking form for my restaurant. The idea is that I can weigh for example a partially full bottle of Vodka (for example!) and from that weight the volume in milliliters will be automatically calculated based on the weight (adjuster) and density of the product.
The code is automatically generated with PHP. Here is an example, I choose which bottle of vodka and based on that choice I would like to display the amount in the span '1_liveWeight'. The problem I am having due to my limited experience is with this line of code:
var qty = (weight - adjuster) * density;
I would like it to function like this:
var qty = (weight - adjuster_!value selected from item_1!) * density!value selected from item_1!
The bits between the ! being where I would like to insert the value.
Below is an extract of the code generated in php.
HTML
<select id='item_1'>
<option value='3'>Smirnoff Vodka 1000ml</option>
<option value='4'>Absolute Vodka 750ml</option>
</select>
<input type='hidden' id='adjuster_3' value='140'>
<input type='hidden' id='density_3' value='0.96'>
<input type='hidden' id='adjuster_4' value='100'>
<input type='hidden' id='density_4' value='0.96'>
<input type='text' id ='weight_1' name ='weight'>
<span id='1_liveWeight'>0</span>
JQuery
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val();
var adjuster3 = $('#adjuster_3').val();
var density3 = $('#density_3').val();
var adjuster4 = $('#adjuster_4').val();
var density4 = $('#density_4').val();
var weight = $('#weight_1').val();
var qty = (weight - adjuster)*density+item;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
});
});
I hope I've explained my issue well enough! Thanks for the help,
DB
You need to assign the correct adjuster and density variable based on the item selection:
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val();
var adjuster3 = $('#adjuster_3').val();
var density3 = $('#density_3').val();
var adjuster4 = $('#adjuster_4').val();
var density4 = $('#density_4').val();
var weight = $('#weight_1').val();
weight = Number(weight);
var adjuster, density;
if(item == 3){
adjuster = Number(adjuster3);
density = Number(density3);
}
else if(item == 4){
adjuster = Number(adjuster4);
density = Number(density4);
}
var qty = (weight - adjuster) * density;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
});
});
I'd probably do it something more like this:
$(document).ready(function(){
var density = 0;
var adjuster = 0;
$("#item_1").change(function(){
recalculateWgt();
});
$("#weight_1").keyup(function(){
recalculateWgt();
});
recalculateWgt();
function recalculateWgt() {
var item = $('#item_1').val();
var adjuster = $('#adjuster_' + item).val();
var density = $('#density_' + item).val();
var weight = $('#weight_1').val();
var qty = (weight - adjuster)*density+item;
$("#1_liveWeight").html("<b>"+ qty +"</b>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='item_1'>
<option value='3'>Smirnoff Vodka 1000ml</option>
<option value='4'>Absolute Vodka 750ml</option>
</select>
<input type='hidden' id='adjuster_3' value='140'>
<input type='hidden' id='density_3' value='0.96'>
<input type='hidden' id='adjuster_4' value='100'>
<input type='hidden' id='density_4' value='0.96'>
<input type='text' id ='weight_1' name ='weight'>
<span id='1_liveWeight'>0</span>
You could use $("#weight_1").change() if you preferred to have the value update only when the quantity field loses focus.
I would say vodka really helped me a lot to understand but still i couldn't figure out - do you need details for just the selected product or for all when your dropdown changes? .Anyway here is something
$(document).ready(function(){
$("#item_1").change(function(){
var item = $('#item_1').val(); // may be 3 or 4 or whatever depends on choice
var adjuster = $('#adjuster_'+ item).val(); // dynamic selector
var density = $('#density_'+item).val();
var weight = $('#weight_'+item).val();
var qty = (weight - adjuster)*density; // density is constant at a given temp. for given liquid why were you chaging this? dilluting?
$("#"+item+"_liveWeight").html("<b>"+ qty +"</b>");
});
});
I ended up solving the problem by learning about eval()
It worked as intended:
eval("var chosenAdjuster = adjuster"+item);
eval("var chosenDensity = density"+item);
var qty = (weight - chosenAdjuster) * chosenDensity;

Categories

Resources