Issues outputting text via JavaScript - javascript

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!

Related

How to fix Javascript multiplication onchange

I'm not sure why my code isn't multiplying the two numbers when I change them. Once I enter a number in the Multiplier field, the onchange function continues adding values and if its a null value, it enters "NaN"
<body>
<h1>Mutiply</h1>
<p>Multiplicand: <input type="text" id="multiplicand" value="0" onchange="multiply()"></p>
<p>Multiplier: <input type="text"/ id="multiplier" value="0" onchange="multiply()"></p> <br>
<div>
<p><span id="showMulipicand">0</span>
×
<span id="showMultiplier">0</span> = <span id="showProduct">0</span></p>
</div>
<script src="multiply.js"></script>
multiply() {
var multiplicand = document.getElementById('multiplicand').value;
var multiplier = document.getElementById('multiplier').value;
var showProduct = parseInt(multiplicand) * parseInt(multiplier);
var p = document.getElementById('showProduct');
p.innerHTML += showProduct;
}
You are appending the result to the content of your p tag.
If you just want to show the result, you have to override the innerHTML instead of appending to it.
p.innerHTML = showProduct;
Also, if you want to update the result as you type, use the oninput event instead of onchange which will only trigger when you leave the <input> field.
If you also want to update the multiplier and multiplicand fields, just do the same as for the product:
document.getElementById('showMulipicand').innerHTML = multiplicand;
To avoid NaN problems, when you read the multiplier/multiplicand from the <input>, do a logical or with 0, this way, if the field is blank, its value will be 0.
You should also change the <input> type from text to number.
Here is the code for showing the multiplication result:
function multiply() {
const multiplicand = document.getElementById('multiplicand').value || 0;
const multiplier = document.getElementById('multiplier').value || 0;
const product = parseInt(multiplicand) * parseInt(multiplier);
document.getElementById('showMulipicand').innerHTML = multiplicand;
document.getElementById('showMultiplier').innerHTML = multiplier;
document.getElementById('showProduct').innerHTML = product;
}
<h1>Mutiply</h1>
<p>Multiplicand: <input type="number" id="multiplicand" value="0" oninput="multiply()"></p>
<p>Multiplier: <input type="number" id="multiplier" value="0" oninput="multiply()"></p>
<p>
<span id="showMulipicand">0</span> ×
<span id="showMultiplier">0</span> = <span id="showProduct">0</span>
</p>

How to use DOM referenced .value's in different scopes? (refactoring/scope issue)

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.

Sort Number in a Textbox on Ascending order using keypress function - HTML

Hi I'm new in the community.
I am trying to create a simple page where in there are 3 textbox. 1st text box is where the number will be entered. For 2nd and 3rd textbox is where the result will be shows on a different format as soon as the numbers are entered from the 1st textbox. 2nd text box should show the number with a comma which I was able to do. Example: As soon as I enter a number on the first text box 22 55 01 02 the 2nd text box will show 22,55,01,02 however on the 3rd textbox it should show the same number from 2nd textbox but on Ascending order which I weren't able to do so. Tried searching for a solution already but to now avail. Maybe I am just missing something. Any help will be very much appreciated.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// code for textbox 3 that didn't work
//function sortAscending(a, b)
//{return a - b;
// }
//var points = boxx3.value;
//points.sort(sortAscending);
//document.getElementById("boxx3").innerHTML = points;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<B><br><center>PASTE HERE</br>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>11x5 GAMES</BR>
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games</br>
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="points.sort(sortAscending)">
</body>
It's actually incredibly simple to sort numbers in JavaScript. All you need to do is:
Split the initial string into an array with .split(" ") (splitting on a space).
Sort the numbers with .sort().
Join the numbers back to a string with .join().
Keep in mind that as the output box is an <input>, you'll need to use .value instead of .innerHTML:
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// Fixed code for sorting the numbers
var points = boxx1.value.split(" ");
document.getElementById("boxx3").value = points.sort().join();
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<body>
<br>
<center>
<b>PASTE HERE</b>
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()" onKeyUp="boxx1KeyPress()">
<br>
<br>
<input type="button" Value="Clear Field" onClick="ClearField()">
<br>
<br>
11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>
Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend">
</center>
</body>
Also note that you had some slightly invalid HTML in your above snippet (primarily that <br> is a void element, so the tag self-closes and thus </br> is not valid). I've cleaned up the HTML in my snippet above.
Hope this helps! :)
Your main issue is that you are trying to sort something that is still a string... you have to make your string into an array first.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var x = s;
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
// get an array from our string s
var arr = s.split(',');
arr.sort(); // note that for strings or ints, the default sort is ascending
document.getElementById("boxx3").innerHTML = arr.join(',');
}
I used the String.split method to get an array, separated at the commas, and the Array.join method to turn it back into a string after it was sorted.
Convert comma separated string into Array. Use array sort function and you done.
function boxx1KeyPress() {
var boxx1 = document.getElementById("boxx1");
var s = boxx1.value.replace(/[ ,]+/g, ",");
var lblValue = document.getElementById("boxx2");
lblValue.value = "" + s;
}
function sortDisending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return b-a});
document.getElementById("boxx3").value = numberArray;
}
function sortAsending() {
var numberArray = document.getElementById("boxx2").value.split(",");
numberArray.sort(function(a, b){return a-b});
document.getElementById("boxx3").value = numberArray;
}
function ClearField() {
document.getElementById("boxx1").value = "";
document.getElementById("boxx2").value = "";
document.getElementById("boxx3").value = "";
}
<B><br><center>PASTE HERE
<input id="boxx1" type="text" onKeyPress="boxx1KeyPress()"
onKeyUp="boxx1KeyPress()">
<br>
<br>
<br>11x5 GAMES
<span id="lblValue"></span>
<input id="boxx2" type="text">
<br>
<br>Keno Games
<input id="boxx3" type="text">
<br>
<p id="Keno"></p>
<input type="button" Value="Ascend" onClick="sortAsending()">
<input type="button" Value="Descend" onClick="sortDisending()">
<input type="button" Value="Clear Field" onClick="ClearField()">

Pixel to cm conversion script not working

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;
};

Saving a Value, and adding to it

There are a few ways this can be asked, I'm trying to go with the easiest. Basically, I have two fields... one is to add a number, the other is to subtract. What I want, is when a number is input into either (let's just stick with the add input for now) and have it update at the bottom once the button "+" is pressed. I want that result to stay at the bottom, so when a new value is put into the add box and the button is pressed, it ADDS to the previous total. For the life of me, I can't figure this one out. Once resolved, I'll take care of the subtraction on my own, just need a push in the right direction. The current code is as follows.
<div id="entire">
<div id="content">
<input type="number" id="addInput" placeholder="0">
<button type="button" id="addBtn" onclick="add()">+</button>
<br>
<br>
<input type="number" id="subInput" placeholder="0">
<button type="button" id="subBtn" onclick="sub()">-</button>
<br>
<br>
<div id="totalAmt"></div>
<br>
<input type="button" id="clear" onclick="clearFields()" value="Clear">
<input type="button" id="reset" onclick="reset()" value="Reset">
</div>
</div>
function add() {
var addInput = document.getElementById("addInput").value;
var emptyValue = "";
var total = emptyValue + addInput;
document.getElementById("totalAmt").innerHTML = total;
}
function clearFields() {
document.getElementById("addInput").value = "";
document.getElementById("subInput").value = "";
}
function reset() {
document.getElementById("totalAmt").innerHTML = "";
}
A link to my codepen is below:
http://codepen.io/0ktane/pen/NNdbOq
Your problem is these two lines
var emptyValue = "";
var total = emptyValue + addInput;
when you are concatenating to a string, you get a string back.
Also, you are not even considering the previous value at first place.
Try this, updated pen
function add() {
var addInput = parseInt(document.getElementById("addInput").value); //parse the value to an integer first
var totalAmt = parseInt(document.getElementById("totalAmt").innerHTML); //parse the value to an integer first
totalAmt = isNaN(totalAmt) ? 0 : totalAmt; //if the value is NaN(not a number) reset it to 0
addInput = isNaN(addInput) ? 0 : addInput;//if the value is NaN(not a number) reset it to 0
document.getElementById("totalAmt").innerHTML = totalAmt + addInput ; //output the correct value
}
var total = 0;
function add() {
var addInput = parseInt(document.getElementById("addInput").value);
total = total + addInput;
document.getElementById("totalAmt").innerHTML = total;
}

Categories