Using javascript to get a value from html input - javascript

I am new to this forum and I want to be able to get a value from my html inputs into javascript. Right now i have this code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PWS</title>
</head>
<body bgcolor="#009933" text="#FFFFFF">
<H1 align="center">PWS Julia en Sophie</H1>
<hr>
<br>
<strong>DOUCHE</strong>
<table>
<tr>
<td>Temperatuur</td>
<td><input type="text" name="dtemp" onClick="calculateTotal()" /></td>
</tr>
<tr>
<td>Tijd</td>
<td><input type="text" name="dtijd" onClick="calculateTotal()" /></td>
</tr>
<tr>
<td>Hoe vaak per week</td>
<td><input type="text" name="dfreq" onClick="calculateTotal()" /></td>
</tr>
</table>
<br>
<strong>BAD</strong>
<table>
<tr>
<td>Temperatuur</td>
<td><input type="text" name="btemp" onClick="calculateTotal()" /></td>
</tr>
</tr>
<tr>
<td>Hoe vaak per week</td>
<td><input type="text" name="bfreq" onClick="calculateTotal()" /></td>
</tr>
</table>
<script type="text/javascript">
var dTemp = document.getElementsByName("dtemp").value;
document.write(dTemp);
</script>
obviously, its not working. Because the dTemp value stays undefined.
Can anyone help me, thanks in advance,
Bob

document.getElementsByName returns an array, so you have to reference the position of the element:
var dTemp = document.getElementsByName("dtemp")[0].value;
I would also recommend giving ID's to your inputs, since it seems that each name is unique in your case, that way you could use document.getElementById

document.getElementsByName("dtemp") will give you array of elements, traverse through one by one and get the value from it.
var elements = document.getElementsByName("dtemp");
var firstValue = elements[0].value;

1) You need to index the result of getElementsByName, as described in other answers; append [0] to document.getElementsByName("dtemp").
2) You can’t use document.write in code that is executed after the page has loaded. It would replace the current document by the written content. Write to an element instead.
3) You have not defined the function calculateTotal at all. Wrap your JavaScript code in a function, e.g.
<div id=result></div>
<script>
function calculateTotal() {
var dTemp = document.getElementsByName("dtemp")[0].value;
document.getElementById('result').innerHTML = dTemp; }
</script>
4) You have a long way to go, since now your code makes no attempt at calculating anything, you should hardly use onclick on an input element to start the calculation (rather, onchange on it, or onclick on a separate button element). You should read a good JavaScript primer, really.

Related

Automatic multiplication for several row

I'm new on coding, then any help will greatly appreciated.
I'm trying to make automatic multiplication from 2 value. Basically my table looks like this. Multiplication works perfectly on the first row. If I make another row by simply copying this code:
<tr>
<td><input id="box1" type="text" oninput="calculate()" /></td>
<td><input id="box2" type="text" oninput="calculate()" /></td>
<td><input id="result" /></td>
</tr>
then the second row won't work. This may happen because the id on second row exactly same with the first row. But if I change the id, the script won't work either. Would you please show me how to fix it?
EDIT: I use this scrip for multiplication purpose:
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
var result = document.getElementById('result');
var myResult = myBox1 * myBox2;
result.value = myResult;
}
I would bind a single input event handler to the table, which will catch any input events on any of the table cells' input elements. Within the handler event.target will refer to the input element where the event originated, and you can use DOM navigation properties/methods to find the associated table cells in the same row.
Maybe a little something like this, using class instead of id:
document.getElementById("multiplier").addEventListener("input", function(e) {
var row = e.target.parentNode.parentNode
var val1 = row.querySelector(".valOne").value
var val2 = row.querySelector(".valTwo").value
row.querySelector(".result").value = val1 * val2
})
<table id="multiplier">
<tr>
<td><input class="valOne" type="text" /></td>
<td><input class="valTwo" type="text" /></td>
<td><input class="result" /></td>
</tr>
<tr>
<td><input class="valOne" type="text" /></td>
<td><input class="valTwo" type="text" /></td>
<td><input class="result" /></td>
</tr>
<tr>
<td><input class="valOne" type="text" /></td>
<td><input class="valTwo" type="text" /></td>
<td><input class="result" /></td>
</tr>
</table>
Further reading:
.addEventListener() method
.parentNode property
.querySelector() method
It would be better to use e.target.closest("tr") instead of e.target.parentNode.parentNode, but note that the .closest() method isn't supported in IE so you would need to use a polyfill.
Note that the JS that I've shown would need to be in a script element that is after the table (e.g., at the end of the body right before the closing </body> tag), or you'd need to wrap it in a document load or DOMContentLoaded handler.

How to get a number value from an input field?

I have some issues with calculating some stuff with JS and getting the right values out of the input fields (number). When I use this code it doesn't show anything. So what is wrong with my JS? Do I need to include a jQuery file?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td><input type="number" name="TotalProductionTime" placeholder=""> hours</td>
</tr>
<tr>
<td>Breaks</td>
<td><input type="number" name="Breaks" placeholder=""> minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td><input type="number" name="Malfunctions" placeholder=""> minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td><p id="test"></p></td>
</tr>
</table>
<input type="button" onclick="Calculate()" name="Calculate" value="calculate">
<script>
function Calculate()
{
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
</script>
</body>
</html>
You had some mistakes in your HTML, but here is a working JSFiddle: Fiddle
You you are trying to get elements by their ID, but you don't give them an ID you give them a Name. Also, stop using inline JavaScript calls; it is bad practice.
function Calculate() {
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td>
<input type="number" id="TotalProductionTime" placeholder="">hours</td>
</tr>
<tr>
<td>Breaks</td>
<td>
<input type="number" id="Breaks" placeholder="">minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td>
<input type="number" id="Malfunctions" placeholder="">minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td>
<p id="test"></p>
</td>
</tr>
</table>
<input type="button" onclick="Calculate()" value="calculate">
</form>
Every id must be converted to integer. Example
var Malfunctions = parseInt(document.getElementById("Malfunctions").value);
then your ready to go
With HTMLInputElement you can use property .valueAsNumber which returns a numeric property if possible:
const str = document.querySelector("input").value;
const num = document.querySelector("input").valueAsNumber;
console.log(typeof str, str, str + 2);
console.log(typeof num, num, num + 2);
<input type="number" value="40" disabled />
You've got two problems here. One obvious is that you try to get a reference to the form inputs by id, but didn't give them any (you gave them a name). To fix, either change the name attribute to an id, or use the form-specific way to reference them, e.g.:
var TotalProductionTime = document.forms.frm1.TotalProductionTime
Second problem is more vicious and has to do with the scope of execution of what you put in onclick attributes. You see, your button is named "Calculate" just like your function, and in the context of the onclick attribute, its parent form is used to resolve identifiers before the global scope. So instead of calling the function named Calculate, you're trying to call the button itself. Fix that by giving them different names, referencing window.Calculate explicitly, or much better, define your event handler in JavaScript instead of using the HTML attribute:
document.forms.frm1.Calculate.onclick=Calculate

How to get elements' value in Javascript

I've the follow code for get the value fot two input and send it to a Ajax file for proccess it. It doesn't work and I put an alert for see what's wrong and the alert return me [object HTMLInputElement].
<tr>
<td>Introduzca licencia: </td>
<td><input type="text" id="lic" name="lic" value=""/></td>
</tr>
<tr>
<td>Introduzca apellidos: </td>
<td><input type="text" id="ape" name="ape" value=""/></td>
</tr>
<script type="text/javascript">
var lic=document.getElementById("lic").value;
var ape=document.getElementById("ape").value;
</script>
<tr>
<td><input type="button" value="Buscar" onclick="load(lic, ape);"/></td>
</tr>
If I try that it return the value of the input
<script type="text/javascript">
function prueba(){
var lic=document.getElementById("lic").value;
var ape=document.getElementById("ape").value;
alert("La licencia es: "+lic+" y los apellidos son: "+ape);
}
</script>
<tr>
<td><input type="button" value="Buscar" onclick="prueba();"/></td>
I don't know why the first code doesn't work if I'm making the variables of the same way.
In the onclick handler (load(lic, ape);) for <input type'='button'> in the first code block, neither the load function nor the two arguments (lic and ape) are defined.
Change it to:
onclick="load();"
and make your script file as:
function load(){
var lic = document.getElementById("lic").value,
ape = document.getElementById("ape").value;
alert("lic is " + lic); // test
alert("ape is " + ape); // test
}
DEMO
P.S. You are missing <table> tags. And document.getElementById will always return a DOM object.

unedined output in javascript alert box

I have written simple jsp file which contain textfield for username and password.
I want to validate that field using javascript, but when I write
var a=document.getElementsByID("uname") and prints length of a, it shows me output as 'undefined'.
here is my code..
<head>
<script>
function validate() {
var a=document.getElementById("uname");
alert(a.length);
return false;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form method="post" action="/Edzeal/Validate">
<table align="center">
<tr>
<td>User Name:</td>
<td><input type="text" name="uname" id="uname"></td>
<td><p id="uerror"></p></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr></tr>
<tr>
<td><input type="submit" value="Login" onclick="return validate()"></td>
<td><input type="reset">&nbspRegister</td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
You are trying to alert the 'length' property of the reference to that element. Element objects do not have any such property, unlike arrays or strings, so you are seeing 'undefined'.
See the docs for Elements: https://developer.mozilla.org/en-US/docs/Web/API/element
And document.getElementById
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
Element has no property length on it, it being undefined is expected.
https://developer.mozilla.org/en-US/docs/Web/API/element?redirectlocale=en-US&redirectslug=DOM%2Felement
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
Just change
alert(a.length);
to
alert(a.value);
a is an Element, no the string value of the form field. You need .value to get that.

JavaScript: how to access the textbox in the second row of the table

I have an html code like this -
<table border="0" cellspacing="2" cellpadding="2" width="99%" id="subAccTable">
<tr>
<h2>Sub Accounts</h2>
</tr>
<tr>
<th>action </th>
<th>account</th>
<th>homeDir</th>
<th>primaryGroup</th>
</tr>
<tr>
<td><input type="hidden" name="vtierId" value="" /></td>
<td><input type="text" name="subAcc"
value=""/></td>
<td><input type="text" name="subHomeDir"
value=""/></td>
<td><input type="text" name="subPriGroup"
value=""/></td>
</tr>
</table>
Now i want to fill the values of textboxes named subAcc, subHomeDir, subPriGroup using javascript. How can i do it ?
There are multiple ways to get the proper DOMElement; including:
Giving each element an id and getting it using document.getElementById
Using document.getElementsByName. This is not preferred since there can be multiple elements with the same name, however there can be only one with the same id.
Using the form directly. For example if your form's name is form1: form1.subAcc
Using document.getElementsByTagName('input') and then getting the proper index.
I'd recommend using the id to retrieve the proper element.
The easiest way would be to give these textboxes a unique id, then reference them like this:
<input type="text" id="subHomeDir" name="subHomeDir" value=""/>
var tb = document.getElementById("subHomeDir");
tb.value = "foo";
If you're stuck with the names only, then you can use document.getElementsByName, just remember, this will return a collection of elements (since names are not necessarily unique), which you'll have to index:
var tb = document.getElementsByName("subHomeDir")[0];
tb.value = "foo";

Categories