Im having trouble with this javascript. here is a n example
window.onload = initPage;
var euro;
var convert;
function initPage()
{
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
}
function calcAnswer()
{
//alert(document.getElementById("conversionType").value);
var value1 = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
//alert(conversionType);
if(var value = document.getElementById("conversionType").value=="polish");
document.getElementById("answer").value=(value1-32)/9*5;
else
document.getElementById("answer").value=value1*9/5+32;
}
here is the html
<h1>Currency Converter</h1>
<form name="convert">
Choose which currency you would like to convert to the Euro:
<select id="conversionType">
<option value="polish">Polish Zloty</option>
<option value="ukraine">Ukraine Hryvnia</option>
</select>
</br>
</br>
<hr>
Amount:<input id="amount" type="text" />
<input id="convertButton" type="button" value="Convert->"/>
To:
<input id="answer" type="text" name="answer" readonly="readonly"/>
</form>
im using an old temperature converter and havent changed that part part but even that part is not working.
For starters, these two lines are wrong:
document.getElementById("convertButton").onclick = calcAnswer();
document.getElementById("conversionType").onchange = calcAnswer();
Change them to:
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
You want to assign a function reference to onclick and onchange, not actually call the function and assign the return value.
Then, fix the if statement in calcAnswer like this:
function calcAnswer()
{
var amount = document.getElementById("amount").value;
var conversionType = document.getElementById("conversionType").value;
var answerElement = document.getElementById("answer");
//alert(conversionType);
if(conversionType == "polish") {
answerElement.value = (amount-32)/9*5;
} else {
answerElement.value = amount*9/5+32;
}
}
Should be
document.getElementById("convertButton").onclick = calcAnswer;
document.getElementById("conversionType").onchange = calcAnswer;
(without the parens)
You just need to reference the function, not execute it.
Related
I'm starting studying the DOM in javascript and I'd like to create a program which makes the sum of two numbers given on input and show it.
I'd like to know what functions should I use, and what functions it is better I didn't.
This is my (very simple) html code:
let warp = document.getElementById('warp');
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
let res = document.getElementById('res');
//res.addEventListener('click', calcul);
//res.onclick(calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul(first, second) {
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>
let answerElemenet = document.createElement("h1");
// You can create a h1 element to display your answer after calculating it
document.body.appendChild(answerElemenet);
// Inside the calculate Function you get the values of input one and two
// and then you store the sum value in a variable and just change your
// answerElement to have the innerHTML value of the finalSum Variable
function calculate(){
let valueOne = parseFloat(document.getElementById('first').value);
let valueTwo = parseFloat(document.getElementById('second').value);
let finalSum = valueOne + valueTwo;
answerElemenet.innerHTML = finalSum;
}
Welcome to Stackoverflow!
I copied your answer and made some small changes. Here comes a brief description and explanation of what you could do better:
If you don't plan to change these references use const instead of let. Also try to keep input elements separated from their values. The reference to the input probably won't change but their value most certainly will.
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
When calculating input values, you usually want them as fresh as possible so instead of saving input values right at the beginning of the script, you get them when you need them, in the calcul() function.
You will also need some kind of validation. Here we try to convert the input to a number and set to zero if not possible:
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
The preferred way of adding event handlers to DOM elements is using the event API. So to call the calcul()function you use the line you had commented:
res.addEventListener('click', calcul);
This also means you should remove the onClick attribute from the DOM. Also, input cannot have children:
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
All together looks like this:
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
res.addEventListener('click', calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
</form>
<div>
</body>
Keep up the good job and never stop asking questions!
This will work. You just need to call the values based on their id in the calcul() function itself.
let warp = document.getElementById('warp');
let res = document.getElementById('res');
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul() {
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
if(isNaN(one) || isNaN(two)){
event.preventDefault();
return
}
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>
https://codepen.io/kev_daddy/pen/MMWEMG
I am building a form that is meant to update the difference between two values in real time (ie without refreshing the page). It is comprised of multiple fields, but ultimately I'll be getting the sum of two values, and displaying this using HTML.
The entire thing appears to work as intended until I get to the function that is meant to display the sum in html.
The intention is that the result (a hidden field) is shown as plain text in output. It doesn't trigger on the onset, however if i punch in an extra character using my keyboard, the event is finally heard and the text shows. up.
I am sure that I am missing something, but how do I ensure that the sum is outputted?
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult; }
var input = document.getElementById("result");
var output = document.getElementById("output"); input.addEventListener("input", function() {
output.innerText = this.value;
});
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!
There is no input event on span. You can create a separate function and pass the value of the calculation to this function whose responsibility will be to update the span text content
function calculate() {
var x = document.getElementById('fee_selector_holder').value || 0;
var y = document.getElementById('content').value || 0;
var result = document.getElementById('result');
var myResult = parseInt(x) + parseInt(y);
result.value = myResult;
updateText(myResult)
}
function updateText(val) {
document.getElementById("output").innerText = val;
}
<input type="text" name="hostelfees" id="content" oninput="calculate()">
<input type="text" name="fee_id" id="fee_selector_holder" oninput="calculate()">
<input type="text" id="result" name="totalfee">
<hr>
<p>You can earn <span id="output"></span> more!
Thanks for stopping by! I have a piece of working code here at JSFiddle
It's a basic sort of a calculator that takes 4 values, runs them through a function and spits out the result. It works as expected until I try to refactor the code. As soon as I try to refactor it at least like this, which gives me NaN or 0 whatever I do.
Here's the original code itself
<!DOCTYPE html>
<html>
<body>
See how rich you can get just flipping stuff
<input type="number" id="bp" placeholder="Buying price">
<input type="number" id="n" placeholder="Amount">
<input type="number" id="sp" placeholder="Selling price">
<input type="number" id="t" placeholder="Tax % (1 by def, 3 prem)">
<button id="button" onclick="profit()">Get rich!</button>
<input type="text" id="r" placeholder="Profit (unless ganked)">
<button id="button" onclick="resetOnClick()">More!</button><br>
<p>Thank HumbleOldMan later, go get rich now.</p>
var profit = function(){
var bp = document.getElementById("bp").value;
var n = document.getElementById("n").value;
var sp = document.getElementById("sp").value;
var t = document.getElementById("t").value;
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(result);
document.getElementById("r").value = result;
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
// just couldn't use assigned variables for DOM references for a reason. Must be scope bs or I'm just a noob//
And here is what I tried doing
<script type="text/javascript">
var bp = Number(document.getElementById("bp").value);
var n = Number(document.getElementById("n").value);
var sp = Number(document.getElementById("sp").value);
var t = Number(document.getElementById("t").value);
var r = Number(document.getElementById("r").value);
var result;
var calcProfit = function(bp,n,sp,t,r){
var result = Math.floor((sp*n-(sp*n/100)*t)-bp*n)
console.log(Number(result));
r = Number(result);
}
var resetOnClick = function(){
document.getElementById("t").value =
document.getElementById("sp").value =
document.getElementById("n").value =
document.getElementById("bp").value = "";
console.log("reset clicked");
}
</script>
The question is common. What am I doing wrong? I definitely don't wont to settle for the fist version and get used to doing things just like that. Any assistance will be highly appreciated.
You've to get the value of input fields while after click, not on page load which will give value to NaN because initially all are empty. Get inside the calcProfit function so you'll get updated values.
I have tried a couple different ways and I feel like this one is the closest to working, however it is not working. I was hoping that someone could point out and explain what I am doing wrong. I think that parseFloat could be my issue, but I am not sure.
window.onload = function () {
var purchPrice = document.getElementById('purchPrice');
var warrMile = document.getElementById('warrMile');
var currentMile = document.getElementById('currentMile');
var purchMile = document.getElementById('purchMile');
var mileAdjPerct = 0;
var mileAdjEach = 0;
var mileAdjTotal = 0;
}
function warrUpdate() {
var warrPerct = (parseFloat(currentMile.value) - parseFloat(purchMile.value)) / parseFloat(warrMile.value);
var warrEach = parseFloat(purchPrice.value) * warrPerct;
var warrTotal = warrEach * 4;
parseFloat(document.getElementById('mileAdjPerct').value = warrPerct);
parseFloat(document.getElementById('mileAdjEach').value = warrEach);
parseFloat(document.getElementById('mileAdjTotal').value = warrTotal);
}
Here is a fiddle: http://jsfiddle.net/hmhxybLL/
There are many issues with your code, the main one is that the variables you want to manipulate are locally scoped in the onload callback function. You have to make the variables global, but that's a bad idea, so among the many things one can do to avoid global variables, one is to encapsulate all your code in a warranty object:
<fieldset id="milewarr" onSubmit="milewarr()">
<p>Purchase Price Per Tire: <input type="number" name="purchPrice" id="purchPrice" onChange="warranty.update();" /></p>
<p>Mileage Warranty: <input type="number" name="warrMile" id="warrMile" onChange="warranty.update();" /></p>
<p>Current Vehicle Mileage: <input type="number" name="currentMile" id="currentMile" onChange="warranty.update();" /></p>
<p>Mileage at Purchase: <input type="number" name="purchMile" id="purchMile" onChange="warranty.update();" /></p>
<br />
<p>Adjustment Percentage: <input type="number" id="mileAdjPerct" readonly /></p>
<p>Adjustment Amount Each Tire: <input type="number" id="mileAdjEach" readonly /></p>
<p>Adjustment Discount Total: <input type="number" id="mileAdjTotal" readonly /></p>
</fieldset>
JS:
var warranty = (function() {
var purchPrice, warrMile, currentMile, purchMile, mileAdjPerct, mileAdjEach, mileAdjTotal;
return {
init: function() {
purchPrice = document.getElementById('purchPrice');
warrMile = document.getElementById('warrMile');
currentMile = document.getElementById('currentMile');
purchMile = document.getElementById('purchMile');
mileAdjPerct = document.getElementById('mileAdjPerct');
mileAdjEach = document.getElementById('mileAdjEach');
mileAdjTotal = document.getElementById('mileAdjTotal');
},
update: function() {
var warrPerct = (currentMile.value - purchMile.value) / warrMile.value; // caution: you should check for a divide by 0 first
var warrEach = purchPrice.value * warrPerct;
var warrTotal = warrEach * 4;
mileAdjPerct.value = warrPerct;
mileAdjEach.value = warrEach;
mileAdjTotal.value = warrTotal;
}
};
})();
window.onload = warranty.init;
http://jsfiddle.net/sebnukem/hmhxybLL/10/
I am VERY NEW to javascript and am messing around with some math. I currently have:
<input disabled="disabled" type="text" id="backer-prediction-answer" width="100" value="" />
<FORM>
<INPUT type="button" value="Apply" name="button1" onclick="apply()">
</FORM>
<script>
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backerPrediction3 = document.getElementById("backer-prediction-3").value;
var backerPrediction4 = document.getElementById("backer-prediction-4").value;
function apply(){
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
document.getElementById("backer-prediction-answer").value = (backers);
}
</script>
I would like to be able to hit apply and have it recalculate. Do I need to delete the variable before declaring it again? If so, how do I do that?
Move the variables backerPredictionX inside the function, so that they are evaluated everytime you apply()
<script>
function apply(){
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
document.getElementById("backer-prediction-answer").value = (backers);
}
</script>
With jquery (code not validated):
function apply(){
var backerPrediction1 = $("#backer-prediction-1").val();
var backerPrediction2 = $("#backer-prediction-2").val();
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
$("#backer-prediction-answer").val(backers);
}