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);
}
Related
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 just started learning javascript. Today trying to learn Map Object Key and Value Pairs. but somehow I see a nonfunctional method of Map namely clear().
whole code I posted below. and line34 and line36 prints same map pairs albeit map object clear method already invoked. where am I wrong ? I just wanna clear the Map object named list_
here is a link you can test and see weirdness: https://codepen.io/KTURKAY/pen/oEpXgb
var list_ = new Map();
var inputkey;
var inputvalue;
var buttonadd;
var buttonclear;
var divlist;
function buttonclearclick(el, ev) {
divlist.innerHTML = '';
console.log(list_);
list_.clear();//I expected, this method should clear it. but indeed it doesn't.?
console.log(list_);
}
function buttonaddclick(c, e) {
list_[inputkey.value] = inputvalue.value;
divlist.innerHTML = "";
for (x in list_) {
let n = document.createElement('div');
n.innerHTML = `${x} = ${list_[x]}`;
divlist.appendChild(n);
}
}
document.body.onload = function(ev) {
inputkey = document.getElementById('inputkey');
inputvalue = document.getElementById('inputvalue');
buttonadd = document.getElementById('buttonadd');
buttonclear = document.getElementById('buttonclear');
divlist = document.getElementById('divlist');
buttonadd.addEventListener('click', buttonaddclick);
buttonclear.addEventListener('click', buttonclearclick);
}
<form>
KEY:
<input type="text" id="inputkey" /> VALUE:
<input type="text" id="inputvalue" />
<input type="button" value="ADD" id="buttonadd" />
<input type="button" value="CLEAR" id="buttonclear" />
</form>
<div id="divlist">
NO DATA
</div>
Some issues:
The items are retrieved in the wrong way from the map. Use the .get method.
The items are not iterated in the correct way. Use for ... of instead of for ... in
See updated script running correctly in this snippet. Comments indicate the corrections:
var list_ = new Map();
var inputkey;
var inputvalue;
var buttonadd;
var buttonclear;
var divlist;
function buttonclearclick(el, ev) {
divlist.innerHTML = '';
console.log('before: ' + list_.size); // To make it work in this snippet
list_.clear();
console.log('after: ' + list_.size); // To make it work in this snippet
}
function buttonaddclick(c, e) {
list_.set(inputkey.value, inputvalue.value); // Use set
divlist.innerHTML = "";
for (const [key, value] of list_) { // Get entries using `of`
const n = document.createElement('div');
n.textContent = `${key} = ${value}`; // Use pair coming from iterator
divlist.appendChild(n);
}
}
document.body.onload = function (ev) {
inputkey = document.getElementById('inputkey');
inputvalue = document.getElementById('inputvalue');
buttonadd = document.getElementById('buttonadd');
buttonclear = document.getElementById('buttonclear');
divlist = document.getElementById('divlist');
buttonadd.addEventListener('click', buttonaddclick);
buttonclear.addEventListener('click', buttonclearclick);
}
<form>
KEY:
<input type="text" id="inputkey" /> VALUE:
<input type="text" id="inputvalue" />
<input type="button" value="ADD" id="buttonadd" />
<input type="button" value="CLEAR" id="buttonclear" />
</form>
<div id="divlist">
NO DATA
</div>
The problem is this:
list_[inputkey.value] = inputvalue.value;
You need to use get and set to work with Maps:
list_.set(inputkey.value, inputvalue.value);
Calling clear() does remove all key/values from the internal Maps Hashmap, but it does not clear the object properties. And if you use the first way of setting properties, you dont actually need a Map but you can use a plain object.
The goal is to type in one text box a certain value (of pixels or centimeters) then to press a button, and the button to do some maths and show the result in a different text box.
What happens is, I'll get a result of 'NaN', implying that the string I inputted hadn't been converted properly. I've gone through hundreds of methods to fix this and it still doesn't work.
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conversion</title>
</head>
<body bgcolor=#FF0000>
<form id="conversions" name="conversions">
Pixel value :
<br>
<input type="text" name="pxvalue" id="pxvalue">
<br>
<input type="submit" name="convertcm" id="convertcm" value="Convert cm to px!">
<input type="submit" name="convertpx" id="convertpx" value="Convert px to cm!">
<br>Centimeter value :
<br>
<input type="text" name="cmvalue" id="cmvalue">
<br>
<br>Output :
<input type="text" name="output" id="output">
</form>
<!-- This is where all the JavaScript code goes -->
<script>
var form = document.getElementById("conversions");
var strcmvalue = form.elements["cmvalue"];
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue);
var pxvalue = ToInteger(strpxvalue);
var output = document.getElementById("output");
var ccmbutton = document.getElementById("convertcm").onclick = cm_to_pixel_conversion(cmvalue);
var cpxbutton = document.getElementById("convertpx").onclick = pixel_to_cm_conversion(pxvalue);
var cm_per_pixel = 0.026458333;
var px_per_cm = 37.795275591;
function pixel_to_cm_conversion(pvalue) {
cmconversion = pvalue / px_per_cm;
output.value = cmconversion.toString();
}
function cm_to_pixel_conversion(cvalue) {
pxconversion = cvalue / cm_per_pixel;
output.value = pxconversion.toString();
}
function ToInteger(x) {
x = Number(x);
return x < 0 ? Math.ceil(x) : Math.floor(x);
}
</script>
<!-- End of the JavaScript code-->
</body>
</html>
Because you are not passing a value to the method, you are passing an html element.
var strcmvalue = form.elements["cmvalue"]; //reference element
var strpxvalue = form.elements["pxvalue"];
var cmvalue = ToInteger(strcmvalue); //passing element, not the value
var pxvalue = ToInteger(strpxvalue);
You need strcmvalue.value or form.elements["cmvalue"].value
Next issue is the fact you read the values when the page loads, so you will only ever have the values from the time it loads.
So you should be reading the values and converting them to numbers inside of your methods, not when the page loads.
After that your click event is calling the function, not referencing it.
var ccmbutton = document.getElementById("convertcm").onclick = function () {
var num = parseInt(strcmvalue.value, 10);
cm_to_pixel_conversion(num);
return false;
};
Why does this code work (As far as it pulls back an empty "CustomerObject" viewable in Chrome console
var CustomerObject = Parse.Object.extend("CustomerObject");
var retrieve = new Parse.Query(CustomerObject);
retrieve.equalTo("customernumber", $('#searchnumber').val());
retrieve.first({
success: function(retrieveResults)
{
}
});
var cname = retrieve.get("customername");
var cnumber = retrieve.get("customernumber");
But this code inside a function does not return any "CustomerObject" when the user clicks the search button?
HTML
<input type="text" name="searchnumber" id="searchnumber" value="" placeholder="Customer Number"/>
<button type="submit" onclick = "search" >Find</button>
JS
function search() {
var CustomerObject = Parse.Object.extend("CustomerObject");
var retrieve = new Parse.Query(CustomerObject);
retrieve.equalTo("customernumber", $('#searchnumber').val());
retrieve.first({
success: function(retrieveResults)
{
}
});
var cname = retrieve.get("customername");
var cnumber = retrieve.get("customernumber");
};
missing bracket <button type="submit" onclick = "search() " >Find</button>
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.