Javascript value of input - javascript

This is supposed to calculate circumference, however, I am only getting a zero returned. What am I doing wrong?
<html>
<head>
<script type="text/javascript">
var index = false;
var text = "This text shifts";
var Pi = 3.14159265;
var dia = document.getElementById("txtdia");
var circumf = dia * Pi;
function DisplayText(){
document.getElementById("txtcircumf").value = circumf;
}
</script>
</head>
<body>
<form>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/><br>
<input type="text" name="txtdia" />
<input type="text" name="txtcircumf" />
<input type="button" value="Change Text" onclick="DisplayText()"/>
</form>
</body>
</html>

The primary problem you have is that this script will run prior to your dom being ready. As a result, even if you were properly grabbing the diameter's value it still wouldn't work, since document.getElementById("txtdia") wouldn't return anything.
I would just fetch the diameter's value each time.
function DisplayText(){
var dia = document.getElementById("txtdia").value;
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
The other option of course is to put this entire script after your html. Ie
</body>
<script type="text/javascript">
var index = false;
var text = "This text shifts";

There are 3 distinct issues which you need to fix for this to work correctly.
txtcircumf and textdia are the name of the elements, not the id, so using document.getElementById will fail.
Fix: Add that as an id onto the elements in question:
<input type="text" name="txtdia" id="txtdia" />
<input type="text" name="txtcircumf" id="txtcircumf" />
The elements are not present when the script first runs. This is the issue described by #AdamRakis and his fix is probably best - always retrieve the value when you need it:
function DisplayText(){
var dia = document.getElementById("txtdia").value;
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}
A minor point, but when you read the .value of a field you get text, as you are doing a mathematical equation it is common practice to ensure the value you're wouking with is numeric. You can use parseFloat for this:
function DisplayText(){
var dia = parseFloat(document.getElementById("txtdia").value);
var circumf = dia * Pi;
document.getElementById("txtcircumf").value = circumf;
}

I made a couple structural changes that improve the overall quality of your code :) (see the arrows for changes)
<html>
<body>
<form>
<input type="text" id="txt1"/>
<input type="text" id="txt2"/><br>
<input type="text" name="txtdia" />
<input type="text" name="txtcircumf" />
<input type="button" id="derp" value="Change Text" /> //<-- added ID, removed inline JS
</form>
<script type="text/javascript">
document.getElementById("derp").onclick = function() { //<-- use this style instead of inline onclicks!
var index = false;
var text = "This text shifts";
var dia = document.getElementById("txtdia").value; //<-- .value, not the whole element!
var circumf = dia * Math.PI; //<-- Math.PI is an object constant, very handy
document.getElementById("txtcircumf").value = circumf;
//no more standard function!
}
</script>
</body>
</html>

Related

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.

JavaScript How to let user type variable in text box solve equation?

I am creating a simple equation solver that involves division. I have two text boxes, One for "Mass" and one for "Element". I want to create a variable "H" and set it equal to 1, that way when the user types in "2" in the mass box and "H" in the element box, the output will say "1".
Here is my HTML
<div id="GramsToMolesContainer"><div id="GramMolesText">
<font size=3>Grams To Moles</font></div>
<form>
Grams : <input type="text" id="GramsChoice" /><br>
Element : <input type="text" id="ElementChoice" /><br>
<input type="button" onClick="GramstoMoles()" Value="Convert" />
</form>
<p>Molar Mass : <br>
<span id = "resultMolarMass"></span>
</p>
</div>
Here is my Javascript:
function GramstoMoles()
{
var H = 1;
GramsState = document.getElementById("GramsChoice").value;
ElementState =
document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML
= GramsState / ElementState;
}
you will need to create a dictionary.
this is how your function should look. every time that you want to add an element - create a new key-value pair.
function GramstoMoles()
{
var elements = {h:1, he:2};
GramsState = document.getElementById("GramsChoice").value;
ElementState =
document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML
= parseInt(GramsState) / elements[ElementState];
}
Check this working snippet of your code!
If you wan to set H as an inital value of some box, do
var ElementState = document.getElementById("ElementChoice").value = H; before you call the function.
function GramstoMoles (){
var H = 1;
var GramsState = document.getElementById("GramsChoice").value;
var ElementState = document.getElementById("ElementChoice").value;
document.getElementById("resultMolarMass").innerHTML = GramsState / ElementState;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="GramsToMolesContainer"><div id="GramMolesText">
<font size=3>Grams To Moles</font></div>
<form>
Grams : <input type="text" id="GramsChoice" /><br>
Element : <input type="text" id="ElementChoice" /><br>
<input type="button" onClick="GramstoMoles()" Value="Convert" />
</form>
<p>Molar Mass : <br>
<span id = "resultMolarMass"></span>
</p>
</div>
When you get the var element and var grams ,
var elements = ['H','He','Li','Be',...];
var atomicmasses = [1,4,6,9,.....];
var molarmass = molarmasses[elements.indexOf(element)];
var mole = grams/molarmass;

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

script not producing result

New to javascript. Would very much like to produce a simple calculator that uses three inputs and 4 fixed values to produce and report a 'peak power output' value. Code is as follows:
<script type="text/javascript">
"use strict";
/*jslint browser:true */
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = document.getElementById('vjump');
hgt = document.getElementById('height');
wgt = document.getElementById('weight');
result = document.getElementById('peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.value = peakresult;
}
</script>
html:
<td>
<input id="vj" type="text" oninput="calculate()" />
</td>
<td>
<input id="hgt" type="text" oninput="calculate()" />
</td>
<td>
<input id="wgt" type="text" oninput="calculate()" />
</td>
have this in a html page with table to display input and results, input works, but not results.
You have jquery tagged, so here is a jQuery version.
<script type="text/javascript">
"use strict";
/*jslint browser:true */
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = $('#vj').val();
hgt = $('#hgt').val();
wgt = $('#wgt').val();
result = $('#peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.val(peakresult);
}
$(document).ready(function() {
$('input[type="text"]').on('blur', function() {
calculate();
});
});
</script>
This assumes you also have <input type="text" id="peakresult" /> in your HTML.
I added a jQuery event handler that will call the calculate button when the user leaves the input field. That could be more useful than having a handler in the field tag.
if you replace
vj = document.getElementById('vjump');
hgt = document.getElementById('height');
wgt = document.getElementById('weight');
by
vj = Number(document.getElementById('vjump').value);
hgt = Number(document.getElementById('height').value);
wgt = Number(document.getElementById('weight').value);
It should work.
BUT WITH NO check for correct input.
(EDITED)
This following code is working (Tested on Chrome)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script>
function calculate() {
var vj, hgt, wgt, result, peakresult;
vj = Number(document.getElementById('vj').value);
hgt = Number(document.getElementById('hgt').value);
wgt = Number(document.getElementById('wgt').value);
result = document.getElementById('peakresult');
peakresult = (78.6 * vj) + (60.3 * hgt) - (15.3 * wgt) - 1308;
result.value = peakresult;
}
</script>
</head>
<body>
<td>
<input id="vj" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="hgt" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="wgt" type="text" oninput="calculate()" value="1"/>
</td>
<td>
<input id="peakresult" type="text" value="0"/>
</td>
</body>
You can use unary plus, +, to turn your values into a number and then perform operations on them:
function add() {
var a = +document.getElementById('firstOperand').value;
var b = +document.getElementById('secondOperand').value;
return a + b;
}
Also your html suggests you are invoking the calculate function every keystroke by using oninput. You can use onblur to call the calculate function after the user leaves the field.
You might need parse text into integer
parseInt(val);
Check this live sample
http://jsfiddle.net/VdrWL/2/
Hope it helps.

In Java Script Text box Name Doesn't like

I don't want to change my text box name in Form because it' using some where else in program.
Problem is JavaScript doesn't like my textbox name (m4j-117). it's Considering "-" as minus.
How can I make it work with out change my text box name.
Thanks
Any help will be appreciate.
Here is my Sample Code.
<form name="randform">
<body>
<script language="javascript" type="text/javascript">
function randomString() {
var chars = "0123456789";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
document.randform.m4j-117.value = "P"+randomstring;
}
</script>
<input type="button" value="Create Random String" onClick="randomString();">
<input type="text" name="name" value="value" onblur="randomString();;"/>
<input type="text" name="m4j-117" value="">
</body>
</form>
How about:
document.getElementsByName("m4j-117")[0].value = "P"+randomstring;
From a specific form:
document.randform.elements["m4j-117"] = "P"+randomstring;
document.randform['m4j-117'].value
Relying on names is a bit antiquated though; I'd suggest giving it an ID and using document.getElementById directly, or using querySelector with an appropriate ID for the form

Categories