JS to perform calculation based on user input - javascript

I have a code where I am trying to calculate a total value based on the value of the input selected by a user. It seems simple but I can't get the total to reflect. Please can someone show me where the fault is?
function calculate() {
var panel = parseInt(document.getElementsById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
}
document.getElementsById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate">Result</button>
<p id="total_hours">result displays here</p>

You need to
use for onclick="calculate()" take the function call, not only the function,
use getElementById, spelling matter,
declare all variables,
and finally move the output inside of the function
function calculate() {
var panel = parseInt(document.getElementById("panel").value),
panelv = 65,
panelt = panel * panelv,
derating_value = 2,
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>

getElementById is singular
declare your vars
call calculate() with brackets
assign the value inside the function
</input> is not needed
Here is a version with eventListeners since other answers already showed you how to fix YOUR version
function calculate() {
var panel = +document.getElementById("panel").value;
if (panel === "" || isNaN(panel)) panel = 0;
let panelv = 65;
let panelt = panel * panelv;
let derating_value = 2;
document.getElementById("total_hours").textContent = (panelt * derating_value);
}
window.addEventListener("load", function() {
document.getElementById("calc").addEventListener("click", calculate)
calculate(); // run at load
})
<input type="number" id="panel" placeholder="panel quantity"><br>
<button type="button" id="calc">Result</button> result displays here: <span id="total_hours"></span>

First, you should call method calculate.
<button type="button" onclick="calculate()">Result</button>
Then, add this line document.getElementsById("total_hours").innerHTML = total_hours_standby; inside calculate function.
Alos, typo error: document.getElementById instead of document.getElementsById

There are couple of issues here:
Most you could have found out if you had looked into console logs.
For starter the function is called getElementById not getElementsById, because there is supposed to be only one element with unique id, so plural does not make sense here.
Another one is a logic error: not updating content after clicking on button i.e when calculate gets executed.
There is also one more syntax error, which is how functions should be passed to HTML element's attribute. It needs to be functionName() instead of functionName
This is how simply fixing this code could look like:
var total_hours_standby = 0;
function calculate() {
var panel = parseInt(document.getElementById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
document.getElementById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
Here I give you couple of ideas for improving it.
Since you use global variable total_hours_standby it may be a good
idea to encapsulate it. So called module pattern should do the job.
New value of total_hours_standby does not seem to depend on an old
one, so I guess you mean to use it somewhere else - in order to do
so, you need to expose it with "public" getter.
If above is not the case, then you don't need total_hours_standby
variable at all and you can just directly return it or display it
without storing this value in variable.
I put code for rendering in separate function - this is because rule
of thumb for functions is that they should have single
responsibility. One functions for calculations, another for rendering
and then one function for handling user's input and click event, that
uses two previous ones. This way if for example you only want to
calculate something without rendering result, then you just, simply can :)
I also stored DOM nodes in variables, instead of calling
getElementById, it is not due to performance, how it is often
assumed, I did it only for better readability.
Constants instead of hard-coded values.
var Calculator = (function() {
const panelInput = document.getElementById("panel");
const output = document.getElementById("total_hours");
const PANEL_V = 65;
const DERATING_VALUE = 2;
const render = value => output.innerHTML = value;
const calculate = value => value * PANEL_V * DERATING_VALUE;
let total_hours_standby = 0;
return {
handleInput: function() {
total_hours_standby = calculate(panelInput.value);
render(total_hours_standby);
},
getTotalHoursStandby: () => total_hours_standby
};
})();
<input type="number" id="panel" placeholder="Panel quantity" />
<button type="button" onclick="Calculator.handleInput()">Calculate</button>
<p id="total_hours">Result displays here</p>

It is typo,
document.getElementsById
should be
document.getElementById

Related

Switch Content of two Textareas using JavaScript

I have two textareas and I like to switch the content of these, so content of the first textarea shall be the content of the second textarea and vice versa. Following code just copy the content of the first textarea into the second, but the second step is not performed, so both textareas comprise the same content afterwards. No error occurs.
function switch_text_content(){
var src_text_memory = src_form.src_message.value;
var trgt_text_memory = trgt_form.trgt_message.value;
console.log(src_text_memory);
src_form.src_message.innerHTML = trgt_text_memory;
trgt_form.trgt_message.innerHTML = src_text_memory;
//switch_text_content2(trgt_text_memory);
}
You are doing in wrong way because you are using .innerHTML to set value instead you can to use .value property to set value of textarea. Like Below Example:
const switchBtn = document.querySelector('#switch-btn');
const firstTextarea = document.querySelector('#first-textarea');
const secondTextarea = document.querySelector('#second-textarea');
switchBtn.addEventListener('click', function() {
const firstContent = firstTextarea.value;
const secondContent = secondTextarea.value;
firstTextarea.value = secondContent;
secondTextarea.value = firstContent;
});
<textarea id="first-textarea">First Content</textarea>
<textarea id="second-textarea">Second Content</textarea>
<br/>
<button type="button" id="switch-btn">Switch</button>

Javascript Uncaught TypeError: Cannot set property 'value' of null

I have checked this question before on SO and was not able to solve it based on the solutions given in other questions.
I am new to javascript and am trying to create a function that converts miles to kilometers and have gotten as far as the function below. I want to set this paragraph element to the value of the conversion.
<p id="kValue"></p>
var kilometersElement = document.getElementById("kvalue");
var milesElement = document.getElementById("mValue");
function convert() {
var km = (milesElement.value * 1.61);
km.toFixed(2);
console.log(km);
document.getElementById("kvalue").innerHTML = kilometersElement;
}
It gets as far as printing the value of km to the console but I am getting the following error when it tries to execute the line below.
Uncaught TypeError: Cannot set property 'value' of null
at convert (cmtk.js:41)
At line 41 I am just calling the function convert();
Can anybody help me?
Most likely, you forgot to give your <input> element an 'id` attribute and value.
<p id="kValue"></p>
<form>
<input id="mValue" type="text" value="">
</form>
<script>
function convertMilesToKm(miles) {
return (miles * 1.61).toFixed(2);
}
var miles = document.getElementById("mValue").value; //assuming textbox
var km = convertMilesToKm(miles);
console.log(km);
document.getElementById("kvalue").innerHTML = km;
</script>
OR
<script>
function showOutput(results, outputElement){
console.log(results);
outputElement.innerHTML = results;
return;
}
function convertMilesToKm(miles) {
return (miles * 1.61).toFixed(2);
}
var km = convertMilesToKm(document.getElementById("mValue").value);
showOutput(km, document.getElementById("kvalue"));
</script>
OR, possibly
<output id="kValue"></output> <!-- HTML5.x only -->
<form>
<input id="mValue" type="text" value="">
</form>
<script>
function showOutput(results, outputElement){
console.log(results);
outputElement.innerHTML = results;
return;
}
function convertMilesToKm(miles) {
return (miles * 1.61).toFixed(2);
}
showOutput(convertMilesToKm(document.getElementById("mValue").value),
document.getElementById("kvalue"));
</script>
Check this link out , it gives you the answer to the error.
Why does jQuery or a DOM method such as getElementById not find the element?
The way you call the values depends on the order in which your code calls it.
Also try to initialize the values of the :
var kilometersElement
var milesElement
function convert(miles) {
return (miles * 1.61).toFixed(2);
}
var kilometersElement = document.getElementById("kValue");
var miles = document.getElementById("mValue");
var kilometers = convert(miles);
console.log(kilometers);
kilometersElement.innerHTML = kilometers;
Make sure you have given id property to the field which you want to fetch using document.getElementById('host').value
You can refer below example
To fetch host value in jsp
document.getElementById('host').value
Try like this:
var kilometersElement = document.getElementById("kValue");
var milesElement = document.getElementById("mValue");
convert();
function convert() {
var km = (milesElement.value * 1.61);
km.toFixed(2);
console.log(km);
kilometersElement.innerHTML = km;
}
<input id="mValue" type="text" value="10"/>
<p id="kValue"></p>
The only issue I see with the code in the question is that in the last line of the convert function, which is setting the innerHTML of the kilometersElement to itself.

"Writing" inside a HTML page using JS and JS scope

I'm developing a program which basically just receives input from the user twice (risk carrier and sum, but that's just a placeholder to make my program less abstract), groups those two values together and then repeats the contents in a loop. See the code below.
<head>
<script type="text/javascript">
function fillArray(){
document.getElementById("danke").innerHTML = "Thanks for specifying the amount of entries.";
var numberOfEntries = parseInt(document.getElementById('input0').value);
var i = 0;
var myArrA = [];
var myArrB = [];
var x = " ";
while(i<numberOfEntries){
var neuRT = prompt("Enter a risk carrier");
myArrA.push(neuRT);
var neuRH = prompt("Enter a risk sum");
myArrB.push(neuRH);
i++;
}
for(i = 0; i<anzahlEintraege; i++){
x = myArrA[i] + " carries a risk of " + myArrB[i];
document.getElementById("test").innerHTML = x;
}
}
</script>
</head>
<body>
<h1>risk assessment</h1>
<input type="text" id="input0" />
<button type="button" onclick="fillArray()">Number of entries</button> <p id="danke"></p>
<button type="button" onclick="untilNow()">Show all entries so far</button>
<br />
<br />
<div id="test"></div>
</body>
</html>
My issues are:
1.) I want to display the array by writing into an HTML element, which I attempted in the for-loop. Pop-ups are to be avoided. How can I loop through HTML elements, such as demo1, demo2, demo3 etc.? I can't just write <p id="demo" + i></p>. What other options are there?
2.) Say I want to make use of the untilNow() function. The scope of my arrays is limited to fillArray(). Do I need to "return" the arrays to the untilNow() function as parameters?
Thanks everyone!!!
The problem with your current code is that you're replacing the html by the last value in every loop. You're using = rather than +=. So, a quick fix would be to replace:
document.getElementById("test").innerHTML = x;
by:
document.getElementById("test").innerHTML += x;
An example of how you could wrap an array of strings in HTMLElements and add them to your document (note that there are many other ways/libraries to achieve the same result):
var myStrings = ["Hello", "stack", "overflow"];
// Two performance rules:
// 1. Use a fragment to prevent multiple updates to the DOM
// 2. No DOM queries in the loop
var newContent = myStrings.reduce(function(result, str) {
var li = document.createElement("li");
var txt = document.createTextNode(str);
li.appendChild(txt);
result.appendChild(li);
return result;
}, document.createDocumentFragment());
// Actually add the new content
document.querySelector("ul").appendChild(newContent);
<ul class="js-list"></ul>

Inserting object properties into text fields based on drop down menu selection

I have recently started using javascript and perhaps got a little in over my head. I'm trying to create a tool for one of my other hobbies that creates coordinates for fences from x1,y1 to x2,y2.
The part that I am getting hung up on right now is part of the UI. I want the user to be able to select their desired fence from a dropdown menu and then for the rest of the information pertaining to the fence (name, length, width, direction, etc.) to be filled into the input fields below. From there they will be referenced in the math portion which I already have done.
I want the fence pieces to be objects because I'm going to add more eventually and perhaps allow the user to add more and I figured that was the easiest more user friendly way to go about it.
I have managed to get to the point where the options are in the dropdown menu, I can select them, and it will fill the piece name in with the value which is the name but I cannot figure out how to access the length, width, height, etc.
This is my first project outside of Code Academy and a little bit I did 10 years ago in High School. That being said, if you notice that I am doing something else stupid, feel free to point it out. The answers for other's questions here have already been a huge source of help for me as I worked on this, so thank you for that and for the future help.
<script>
//Start Variable Library
var dropMenuPieceName = 0;
var dropMenuPieceName = 0;
//End Variable Library
// Start Function Library
var fencePieceDropDown = function(dropDownMenuID) {
var dropMenu = document.getElementById(dropDownMenuID);
for(var i = 0; i < fenceArray.length; i++) {
var dropMenuOption = document.createElement("option");
var dropMenuPieceName = fenceArray[i].name;
var dropMenuPieceName = fenceArray[i].length;
dropMenuOption.innerHTML = fenceArray[i].model;
dropMenuOption.value = fenceArray[i].name;
var dropMenuIndex = 1;
dropMenu.add(dropMenuOption,dropMenuIndex);
};
};
//End Function Library
// Start Fence Object Library
function Fence(name,model,length,width,direction,x_offSet,y_offSet,z_offSet,r_offSet) {
this.name = name;
this.model = model;
this.length = length;
this.width = width;
this.direction = direction;
this.x_offSet = x_offSet;
this.y_offSet = y_offSet;
this.z_offSet = z_offSet;
this.r_offSet = r_offSet;
};
var fenceArray = new Array();
var plot_ohrada = new Fence
("plot_ohrada","plot_ohrada",3,0.1,0.02,0,0,0,0);
fenceArray[0] = plot_ohrada;
var plot_ohrada_pruchozi = new Fence
("plot_ohrada_pruchozi","plot_ohrada_pruchozi",4,0.2,0.02,0,0,0,0);
fenceArray[1] = plot_ohrada_pruchozi;
var plot_ohrada_zlomena = new Fence
("plot_ohrada_zlomena","plot_ohrada_zlomena",5,0.3,0.03,0,0,0,0);
fenceArray[2] = plot_ohrada_zlomena;
//End Fence Object Library
</script>
</head>
<body>
<form name="primPieceSection">
<div align="center">
Piece Model:
<select id="primPieceModel" >
<option value = 0>Custom Piece</option>
<select><br /><br /><br />
Piece Name: <input type="text" id="primPieceName" placeholder="Insert Template Name"><br />
Piece Length: <input type="text" id="primPieceLength" value=0><br />
Piece Width: <input type="text" id="primPieceWidth" value=0><br />
Piece Direction: <input type="text" id="primPieceDir" value=0><br />
</div>
</form>
<script>
var primPieceNameField = document.getElementById("primPieceName");
var primPieceLengthField = document.getElementById("primPieceLength");
var primPieceModelDrop = document.getElementById("primPieceModel");
primPieceModelDrop.onchange = function() {
primPieceNameField.value = this.value; ///this should return the object's name
primPieceLengthField.value = this.value; ///this should return the object's length. I just put in this.value while I was testing it.
};
fencePieceDropDown("primPieceModel");
</script>
In your case, the value of each dropdown option should be not its name, but rather the index of the corresponding fence in the fenceArray, which is i. Then, inside primPieceModelDrop.onchange, you will use fenceArray[this.value] to access the selected fence object.
So, you need to replace this line:
dropMenuOption.value = fenceArray[i].name;
with this:
dropMenuOption.value = i;
And then rewrite the onchange handler as follows:
primPieceModelDrop.onchange = function() {
primPieceNameField.value = fenceArray[this.value].name;
primPieceLengthField.value = fenceArray[this.value].length;
};
What you’re doing is perfectly reasonable for a beginner, but you should understand that it’s a somewhat simplistic, low-level approach. As you become more confident in JS, and as your project grows, you may find it easier to employ a framework such as AngularJS.

Calculating a number using a textbox

I've been trying to calculate a number using a number given by a user in a text box. I've been trying to use the following code. But when I try to test it, nothing happens. Is there something I'm missing? And is there a way that I can make the imprint variable global?
<form>
<p>How many products do you want
ingraved?<input id="imprint_amount" name="imprint_amount" type="text"/>
</p>
<p>Names to be Imprinted(one per
line)<TEXTAREA COLS=25 NAME="imprint_text" ROWS=5 WRAP=HARD style="resize:none;"></textarea>
</p>
<input onclick="imprint_price" type="button" value="Finish"/>
<p id="total_cost"></p>
</form>
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quality,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount');
imprint_total = $imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost') = "$" + imprint_total;
}
Thanks,
Traci
You will want to use the value property of that input element you are referencing in your variable:
… parseInt(imprint_quantity.value, 10);
For arbitrary HTML elements, you need to use textContent (or innerText to support old IE):
document.getElementById('total_cost').textContent = …;
Assigning to an expression as you did should have thrown a quite accurate exception, check your browser's error console for them.
Change your javascript to:
<script type="text/javascript">
function imprint_price() {
var imprint_cost,
imprint_quantity,
imprint_total;
imprint_cost = 10.99;
imprint_quantity = document.getElementById('imprint_amount').value;
imprint_total = imprint_cost * parseInt(imprint_quantity, 10);
document.getElementById('total_cost').innerHTML = imprint_total;
}
</script>
Working jsFiddle here http://jsfiddle.net/Zt38S/2/
In this line, you'll want to set the innerHTML of the element.
document.getElementById('total_cost').innerHTML = "$" + imprint_total;
This basically sets the text inside the <p></p> to be <p>$x.xx</p>.
And also this line should be
imprint_quantity = document.getElementById('imprint_amount').value;
which retrieves the value from the textbox.
Furthermore, when defining the variables, you wrote "quality". It should be
imprint_quantity,
imprint_quantity = document.getElementById('imprint_amount');
=
imprint_quantity = document.getElementById('imprint_amount').value();
Lemme know if that fixes it, a common enough mistake.

Categories