Difference between two fields in HTML using Javascript - javascript

I have searched the web for (what I am expecting to be) a basic answer to this question.
I have an HTML form I am putting together for a specific system. I have two text fields that a user will input two temperatures into. I want to have a third text field that onBlur, will generate the difference between these two temperatures. I have a script which I think is heading in the right direction, but does not work. Because of the system I will be using this for, I cannot have tags in the HTML.
My script:
<script language="javascript" type="text/javascript">
<!--
function calculate_temp(TempIn, TempOut) {
var TempIn = parseInt(document.getElementById('TempIn').value);
var TempOut = parseInt(document.getElementById('TempOut').value);
var Delta = TempIn - TempOut;
document.getElementById('Delta').innerHTML = Delta
}
// -->
</script>
My HTML:
<body>
<div>
<p><label for="TempIn">TempIn: </label><input type="text" name="TempIn" id="TempIn" /></p>
<p><label for="TempOut">TempOut: </label><input type="text" name="TempOut" id="TempOut" /></p>
<p><label for="Delta">Delta: </label> <input type="text" name="Delta" id="Delta" onBlur="calculate_temp(this.form.TempIn.value, this.form.TempOut.value)"/></p>
</div>
</body>
Can anyone explain what I am doing wrong here? Again, I want the user to input TempIn, hit tab, input TempOut, hit tab and then the Delta be calculated automatically.
Like I said, every resource I find online does it a slightly different way, but I can't seem to get it working if I use any of the approaches.
Any help is greatly appreciated. Thanks.

An input doesn't have an innerHTML, you should use value.
document.getElementById('Delta').value = Delta
Also, always pass the 2nd parameter to parseInt which is the radix. Otherwise it will often guess the wrong radix.

Remove the comments in your script: .
All tags and attribute names must be lowercase in XHTML (optional). i.e:
onblur.
For your expected behavior, I recommend use the onfocus event,
it makes more sense.
You don't need to pass nothing to the calculate_temp() function if
you can access the elements through the script.
Change the value of the Delta input with the value property.
Result:
<head>
<title>Untitled 1</title>
<script language="javascript" type="text/javascript">
function calculate_temp(TempIn, TempOut) {
var TempIn = parseInt(document.getElementById('TempIn').value);
var TempOut = parseInt(document.getElementById('TempOut').value);
var Delta = TempIn - TempOut;
document.getElementById('Delta').value = Delta
}
</script>
</head>
<body>
<div>
<p><label for="TempIn">TempIn: </label><input type="text" name="TempIn" id="TempIn" /></p>
<p><label for="TempOut">TempOut: </label><input type="text" name="TempOut" id="TempOut" /></p>
<p><label for="Delta">Delta: </label> <input type="text" name="Delta" id="Delta" onfocus="calculate_temp()"/></p>
</div>
</body>

I'll throw my hat in the ring....
html:
<div>
<p><label for="TempIn">TempIn: </label><input type="text" name="TempIn" id="TempIn"/></p>
<p><label for="TempOut">TempOut: </label><input type="text" name="TempOut" id="TempOut" /></p>
<p><label for="Delta">Delta: </label> <input type="text" name="Delta" id="Delta"/></p>
</div> ​​​​
js:
/* store elements */
var TempIn = document.getElementById('TempIn'),
TempOut = document.getElementById('TempOut'),
Delta = document.getElementById('Delta');
function calculate_temp() {
Delta.value = parseInt(TempIn.value,10) - parseInt(TempOut.value,10);
}
/* unobtrusive onblur */
TempIn.onblur = calculate_temp;
TempOut.onblur = calculate_temp;
Delta.onblur = calculate_temp;
​here's a fiddle: http://jsfiddle.net/JKirchartz/TbHW3/
EDIT should probably mention, this JS should be right above your </body> tag, or be run when the dom has loaded.

The OnBlurevent fires when the control in question looses the focus, so your code can only get called, when the user moves the focus away from the Delta input. You want it to get called when the TempOut input looses it's focus, so that's where your event handling should be setup:
<p><label for="TempIn">TempIn: </label><input type="text" name="TempIn" id="TempIn" /></p>
<p><label for="TempOut">TempOut: </label><input type="text" name="TempOut" id="TempOut" onBlur="calculate_temp(this.form.TempIn.value, this.form.TempOut.value)"/></p>
<p><label for="Delta">Delta: </label> <input type="text" name="Delta" id="Delta" /></p>

try this
script:
<script language="javascript" type="text/javascript">
<!--
function calculate_temp() {
var TempIn = parseInt(document.getElementById('TempIn').value);
var TempOut = parseInt(document.getElementById('TempOut').value);
var Delta = TempIn - TempOut;
document.getElementById('Delta').value = Delta;
}
// -->
</script>
html:
<body>
<div>
<p><label for="TempIn">TempIn: </label><input type="text" name="TempIn" id="TempIn" /></p>
<p><label for="TempOut">TempOut: </label><input type="text" name="TempOut" id="TempOut" /></p>
<p><label for="Delta">Delta: </label> <input type="text" name="Delta" id="Delta" onBlur="calculate_temp()"/></p>
</div>
</body>

<div>
<p><label for="TempIn">TempIn: </label><input type="text" name="TempIn" id="TempIn" onBlur="calculate_temp(document.getElementById('TempIn').value, document.getElementById('TempOut').value);"/></p>
<p><label for="TempOut">TempOut: </label><input type="text" name="TempOut" id="TempOut" onBlur="calculate_temp(document.getElementById('TempIn').value, document.getElementById('TempOut').value);"/></p>
<p><label for="Delta">Delta: </label> <input type="text" name="Delta" id="Delta" /></p>
</div>
<script language="javascript" type="text/javascript">
<!--
function calculate_temp(TempIn, TempOut) {
var Delta = TempIn - TempOut;
document.getElementById('Delta').value = Delta
}
// -->
</script>

Related

Call for multiple values to be displayed in textarea

I'm in the process of trying to create a simple input form web page using both HTML and JavaScript but I am stuck. What I am trying to do is to ask for the following and display them in the textarea:
-First Name
-Last Name
-CRN
-Professor Name
So far I am only able to get the First Name to show on the Results box but no luck with the other. Could use some help, thanks in advance.
My CODE looks like this:
// initialize the counter and the array
var numbernames=0;
var names = new Array();
function SortNames() {
// Get the name from the text field
thename=document.theform["firstn"].value
// Add the name to the array
names[numbernames]=thename;
// Increment the counter
numbernames++;
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Here's a complete different, but more readable approach.
I get all inputs of type text.
I get the textarea that is the target.
loop throug all inputs getting it's value.
inside loop, after getting the value, set it to the textarea
Take a look running the snippet below
// initialize the counter and the array
function SortNames() {
var inputs = document.querySelectorAll('input[type="text"]');
var txtArea = document.querySelector('[name="sorted"]');
//loop the text inputs
inputs.forEach(function(elem){
var valueOf = elem.value;
txtArea.value += valueOf + '\n'; //concat the value
});
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit" onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted"></textarea>
</form>
EDIT
If you REALLY want to keep the way you were doing, here's a solution:
1. Push the values from the inputs directly to the array, then set the value inside the textarea.
// initialize the counter and the array
var names = new Array();
function SortNames() {
names.push(document.theform["firstn"].value);
names.push(thename=document.theform["lastn"].value);
names.push(thename=document.theform["crn"].value);
names.push(thename=document.theform["prof"].value);
document.theform.sorted.value=names.join("\n");
}
<form name="theform">
First Name:
<input type="text" name="firstn" size="10" /><p>
Last Name:
<input type="text" name="lastn" size="10" /><p>
CRN:
<input type="text" name="crn" size="10" /><p>
Professor:
<input type="text" name="prof" size="10" />
<input type="button" name="addname" value="Submit"
onclick="SortNames();">
<h2>Results:</h2>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</form>
Changed the tags to more semantic and functional tags. Used the HTMLFormControlsCollection API to set/get form controls. The output is a Template Literal.
Details Commented in Demo
Demo
// Reference the top form
const reg = document.forms.registration;
// Reference the bottom form
const dis = document.forms.display;
// Collect all inputs from top form
const f = reg.elements;
// When top form is clicked...
reg.onclick = function(event) {
// Collect the data from each input and store it in an Object
const student = {
First: f.first.value,
Last: f.last.value,
CRN: f.crn.value,
Prof: f.prof.value
};
// Call function
displayData(event, student);
}
function displayData(event, student) {
// Reference the textarea
const view = dis.elements.sorted;
// if the element that was clicked had [name=add]...
if (event.target.name === 'add') {
/* Set the textarea's value to a Template Literal with
|| interpolated values from the student Object.
*/
view.value += `
First: ${student.First}
Last.: ${student.Last}
CRN..: ${student.CRN}
Prof.: ${student.Prof}
~~~~~~~~~~~~~~~~~~~`;
// Otherwise quit
} else {
return false;
}
}
input,
label {
font: inherit;
display: inline-block;
}
label {
width: 20%
}
[type=text] {
width: 75%;
}
[type=reset] {
margin: 5px 0 0 85%;
}
<!DOCTYPE html>
<html lang=”en”>
<head>
<title></title>
</head>
<body>
<form id="registration">
<fieldset id='set0'>
<legend>Registration</legend>
<label>First Name: </label>
<input type="text" name="first" size="10" /><br>
<label>Last Name: </label>
<input type="text" name="last" size="10" /><br>
<label>CRN: </label>
<input type="text" name="crn" size="10" /><br>
<label>Professor: </label>
<input type="text" name="prof" size="10" /><br>
<input type="reset" name="add" value="Submit">
</fieldset>
</form>
<form id='display'>
<fieldset id='set1'>
<legend>View Data</legend>
<textarea cols="50" rows="10" name="sorted">
</textarea>
</fieldset>
</form>
</body>
</html>

HTML-Javascript Input-Calculation-Output

I need just want to add some textboxes/form to input data from a user through HTML and take them into variables in a script that will run a calculation and then output the answer to the calculation. I have some code but its not working properly. It seems that when the submit button is clicked, the function isn't called. Any help would be great: here's the code.
<form id="frm1" action="form_action.asp">
Initial Displacement: <input type="number" name="x"><br>
Initial Velocity: <input type="number" name="v"><br>
Acceleration: <input type="number" name="a"><br>
Time Passed: <input type="number" name="t"><br>
<input type="button" onclick="calc()" value="Submit"/>
</form>
<script>
function calc()
{
var b=document.getElementById("frm1");
document.write(b.element[0].value+b.element[1].value*b.element[2].value+(1/2)*b.element[3].value*b.element[2].value*b.element[2].value);
}
</script>
https://jsfiddle.net/zytyf16q/#&togetherjs=qABKDyLpK2
There is a mistype in your code on the submit button. Your submit button should look like:
<!DOCTYPE html>
<html>
<body>
Initial Displacement:
<input type="number" id="x" name="x">
<br> Initial Velocity:
<input type="number" id="v" name="v">
<br> Acceleration:
<input type="number" id="a" name="a">
<br> Time Passed:
<input type="number" id="t" name="t">
<br>
<input type="button" onclick="calc('x','v','a','t')" value="Submit">
</body>
<script>
function calc(x, v, a, t) {
var Displace = parseInt(document.getElementById(x).value)
var Velocity = parseInt(document.getElementById(v).value)
var Acceleration = parseInt(document.getElementById(a).value)
var Time = parseInt(document.getElementById(t).value)
var calculations = Displace + (Velocity * Acceleration) + ((1 / 2) * Time * Acceleration * Time);
alert(calculations)
}
</script>
</html>
I added id's to the inputs, and then used document.getElementById to select them and save them to a variable with their respective name. Then I carried out the calculation.
<form id="frm1" action="form_action.asp">
Initial Displacement: <input type="number" name="x" id="x"><br>
Initial Velocity: <input type="number" name="v" id="v"><br>
Acceleration: <input type="number" name="a" id="a"><br>
Time Passed: <input type="number" name="t" id="t"><br>
<input type="button" onclick="calc()" value="Submit"/>
</form>
<script>
function calc()
{
var x = document.getElementById('x').value
var v = document.getElementById('v').value
var a = document.getElementById('a').value
var t = document.getElementById('t').value
document.write(x+v*a+(1/2)*t*a*a);
}
</script>

Simple Gallon Calculator

I'm attempting to build a simple web form that takes 3 number inputs and outputs one number based on this formula: (a*b*c)/271).
This is the code I have but nothing is displayed in the output.
Clearly I have almost no clue what I'm doing.
I appreciate all help:
<body>
<img id="logo"src="images/a&l.png" alt="A&L Cesspool"/>
<h1>Grease Trap Gallon Calculator<h2>
<form name=calculator">
<input label="length" type="number" id="a">
<input label="width" type="number" id="b">
<input label="height" type="number" id="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6" >
</form>
<script language="JavaScript" type="text/javascript">
<!--
function gallons() {
var LENGTH = document.calculator.a.value;
var WIDTH = document.calculator.b.value;
var HEIGHT = document.calculator.c.value;
var Total =(LENGTH*WIDTH*HEIGHT)/271;
document.calculator.OUTPUT.value = Total;
}
// -->
</script>
document.forms.calculator. There's no such thing as document.calculator. Also, form elements need name attributes to refer to them in form context, not IDs.
In other news
You have unclosed quotes
You have irregular naming conventions (OUTPUT, a, Total)
You have irregular quotes policy (sometimes you have, sometimes you don't).
So basically
<form name="calculator">
<input label="length" type="number" name="a">
<input label="width" type="number" name="b">
<input label="height" type="number" name="c">
<input type=Button value=Calculate onClick="gallons();">
<input name="OUTPUT" id="output" SIZE="4" maxlength="6">
</form>
function gallons() {
var LENGTH = document.forms.calculator.a.value;
var WIDTH = document.forms.calculator.b.value;
var HEIGHT = document.forms.calculator.c.value;
var Total = (LENGTH * WIDTH * HEIGHT) / 271;
document.forms.calculator.OUTPUT.value = Total;
}
Please grab a proper tutorial from MDN or some similar good source, and start reading.
Your call to document.calculator is not finding the element because its looking by id
change your form definition and it will work
<form name="calculator" id="calculator">

Getting values with javascript position()

My shopping cart script is intended to check if an article is already in the shopping cart; then the numbers must be filled in the survey.
I work with Javascript. I give the ID number through a position() function.
This is a part of the script where I pick list:
<input type="text" size="2" name="aantalArts_{position()}" id="aantalArts_{position()}"/>
The output:
<input type="text" size="2" value="" name="aantalArts_1" id="test" class="infoButton">
<input type="text" size="2" value="" name="aantalArts_2" id="test" class="infoButton">
<input type="text" size="2" value="" name="aantalArts_3" id="test" class="infoButton">
<input type="text" size="2" value="" name="aantalArts_4" id="test" class="infoButton">
I am just filling the numbers, but how do I deal with the positions?
<script language="javascript" type="text/javascript">
if(document.all.artNr.value = <%=artNrWW%>);{
document.all.aantalArts_??????.value = <%=aantalWW%>;
}
</script>
You are probably looking for the following syntax:
var i = 1; // or whichever
document.all["aantalArts_" + i].value = <% aantalWW %>;

Copy contents of one textbox to another

Suppose an entry is made in a textbox. Is it possible to retain the same entered text in a second text box? If so, how is this done?
<html>
<label>First</label>
<input type="text" name="n1" id="n1">
<label>Second</label>
<input type="text" name="n1" id="n1"/>
</html>
<script>
function sync()
{
var n1 = document.getElementById('n1');
var n2 = document.getElementById('n2');
n2.value = n1.value;
}
</script>
<input type="text" name="n1" id="n1" onkeyup="sync()">
<input type="text" name="n2" id="n2"/>
More efficiently it can be done as :
For the one who will see the post now should use best practices of javascript.
<script>
function sync(textbox)
{
document.getElementById('n2').value = textbox.value;
}
</script>
<input type="text" name="n1" id="n1" onkeyup="sync(this)">
<input type="text" name="n2" id="n2"/>
<html>
<script type="text/javascript">
function copy()
{
var n1 = document.getElementById("n1");
var n2 = document.getElementById("n2");
n2.value = n1.value;
}
</script>
<label>First</label><input type="text" name="n1" id="n1">
<label>Second</label><input type="text" name="n2" id="n2"/>
<input type="button" value="copy" onClick="copy();" />
</html>
Well, you have two textboxes with the same ID. An Id should be unique, so you should prbably change this.
To set the value from one text box to another a simple call to getElementById() should suffice:
document.getElementById("n1").value= document.getElementById("n2").value;
(assuming, of course you give your secodn text box an id of n2)
Tie this up to a button click to make it work.
This worked for me and it doesn't use JavaScript:
<form name="theform" action="something" method="something" />
<input type="text" name="input1" onkeypress="document.theform.input2.value = this.value" />
<input type="text" name="input2" />
</form>
I found the code here
Use event "oninput". This gives a more robust behavior. It will also trigger the copy function when you copy paste.
You can this way also used copy contents of one textbox to another
function populateSecondTextBox() {
document.getElementById('txtSecond').value = document.getElementById('txtFirst').value;
}
<label>Write Here :</label>
<input type="text" id="txtFirst" onkeyup="populateSecondTextBox();" />
<br>
<label>Will be copied here :</label>
<input type="text" id="txtSecond" />

Categories