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;
};
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 am trying to make a simple webpage where the user enters in a number and the page tells the user whether the number they entered in is even or odd. I would like to display that in the textbox at the bottom of the screen.
However, when I click the button, nothing happens. I even tried to add an "alert" when the button is pressed, but even that doesn't happen. Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script type = "text/javascript">
function oddOrEven(){
var userInput = document.getElementById('number');
var number = number.value;
var output = document.getElementById('display');
alert(number);
if(number % 2 == 0){
output.value = number + " is even!"
}else{
output.value = number + " is odd!"
}
}
</script>
</head>
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>
</html>
Take a look at these three lines here:
var userInput = document.getElementById('number');
var number = number.value;
alert(number);
You've retrieved a reference to the #number element and stored it in the userInput variable. Then, you've created a variable called "number," but the value you assigned to it is a property of the variable you just created.
However, this object reference stored in the number variable doesn't have this property, which is causing a runtime error. Try pressing F12 while in your browser with this script running and see what errors appear in the console.
Instead, try this out and see what reaction you get:
var userInput = document.getElementById('number');
var number = userInput.value;
number = parseInt(number);
I see a couple typos in your code, here's a modified version that I think ought to work:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script type = "text/javascript">
function oddOrEven(){
var userInput = document.getElementById('number');
var number = userInput.value; // you originally had "number.value", but that doesn't make any sense.
number = parseInt(number); // number is initialy a string, we need to convert it to an integer
var output = document.getElementById('display');
alert(number);
if(number % 2 == 0){
output.value = number + " is even!"
}else{
output.value = number + " is odd!"
}
}
</script>
</head>
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>
</html>
You've made a mistake.
You wrote:
var number = number.value;
You should have written:
var number = userInput.value;
I am trying to make it so that when I hit the submit button in html, we value in the input field replaces the item inside of the P element that has the id "numberz".
I can get the code to do that but the website immediately changes back to having the default value in the P element with the id "numberz".
How do I prevent the website from changing back to the default value of the element that is hard-coded into the HTML file?
<!DOCTYPE html>
<html>
<head>
<title>JS test</title>
<script>
function e() {
var x = document.getElementById("numberz");
var z = document.getElementById("num").value;
//alert(x.innerHTML + " s " + z);//
x.innerHTML= z;
};
</script>
</head>
<body>
<p>The number is:</p>
<p id = "numberz">s</p>
<br>
<br>
<form onsubmit = "return e();">
<input id = "num" type = "text" size = "4" placeholder = "test"/>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
Because the form is submitting, you need to cancel the form submission.
function e() {
var x = document.getElementById("numberz");
var z = document.getElementById("num").value;
//alert(x.innerHTML + " s " + z);//
x.innerHTML= z;
return false;
};