How to get a number value from an input field? - javascript

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

Related

please enter a valid value the two nearest valid value is?

my assignment is to make weight calculator but due to limitations of university I am not able to use all tags so I write code it works fine but gives me a error of please enter a valid value the two nearest valid value are ***number*** and ***number***.
I think that is because of the number attribute in input tag but I can not able to find what's wrong and how to correct it.
There is one more error if I only calculate one conversion output flash on screen and vanished if I get output in all fields then answer is shown.
<html>
<head>
<title>Weight Convertor Calculator</title>
<script>
var z;
var x;
function converter() {
if (document.weight.kg.value >= 1) {
x = document.weight.kg.value;
document.getElementById("g").value = x * 1000;
document.getElementById("p").value = x * 2.2046;
document.getElementById("m").value = x * 1000000;
document.getElementById("ut").value = x * 0.0011023;
z = 35.274 * x;
document.getElementById("o").value = z;
} else {
window.alert("please enter any number greater than 0");
}
}
</script>
</head>
<body bgcolor="#b3f0ff">
<h1 align="center" style="color:#ff0066;"> Weight Calculator</h1>
<br>
<br>
<form name="weight" method="post">
<table align="center" style="color:#ff0066;">
<tr>
<td><b>Enter your weight in Kg:</b></td>
<td><input type="number" id="kg" name="kilogram" placeholder="enter_any_number"></td>
</tr>
<tr>
<td align="right"><input type="submit" value="Convert" onClick="converter(kg.value)"></td>
<td><input type="reset"></td>
</tr>
<tr>
<td align="right"><b>weight in Grams=</b></td>
<td><input type="number" id="g" name="gram"></td>
</tr>
<tr>
<td align="right"><b>weight in Pounds=</b></td>
<td><input type="text" id="p" name="pound"></td>
</tr>
<tr>
<td align="right"><b>weight in MilliGrams=</b></td>
<td><input type="number" id="m" name="milligram"></td>
</tr>
<tr>
<td align="right"><b>weight in US Ton=</b></td>
<td><input type="text" id="ut" name="uton"></td>
</tr>
<tr>
<td align="right"><b>weight in Ounces=</b></td>
<td><input type="number" id="o" name="ounce"></td>
</tr>
</table>
</form><br>
<p align="center" style="color:#ff0066;"><b>NOTE: Enter only numerical
value which is greater than 0</b></p>
</body>
</html>
Try adding the attribute step="any" to your input. That helped me.
No need to make input type 'text', just add one attribute step="0.01" with type="number" to accept decimal values.
In number inputs fragments are not allowed, so you need to use an text input.
Your form will be submitted: data gone
Here you can find a demo that works, based on your code.
Changing input typ from number to text will work.

How do I properly set the value of a text field with javaScript?

I'm trying to get the average of 4 grades and pass it in a text field.
It does get the average, the only part that doesn't work is the grade.value = grade; part
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Week #10 JavaScript Assignment: Problem #1</title>
<script type = "text/javascript">
function calcgrade(one,two,three,four){
sum = parseInt(one.value) + parseInt(two.value) + parseInt(three.value) + parseInt(four.value);
grade = sum / 4;
grade.value = grade;
}
</script>
</head>
<body>
<h1>Calculate Grade</h1>
<form>
<table>
<tr>
<th>Assignment #</th>
<th>Grade</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" id="one" name="one"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text" id="two" name="two"></td>
</tr>
<tr>
<td>3</td>
<td><input type="text" id="three" name="three"></td>
</tr>
<tr>
<td>4</td>
<td><input type="text" id="four" name="four"></td>
</tr>
<tr><td colspan="2"><input type="button" onclick="calcgrade(one, two, three, four)" value="Calculate Grade"></td></tr>
<tr>
<td>Grade:</td>
<td><input type="text" id="grade" name="grade"></td>
</tr>
</td>
</form>
</body>
</html>
Use
document.getElementById('grade').value=grade;
you need to get the element in javascript
gradeEle = document.getElementById("grade");
gradeEle.value = grade;
It should be:
document.getElementById('grade').value = grade;
You're trying to reuse grade for 2 different values, but it can only keep one of them.
grade.value = grade;
// ^ element
// ^ division result
You'll either want to use a different variable:
var result = sum / 4;
grade.value = result;
Or, you can skip it entirely:
grade.value = sum / 4;
Though, do note that automatic globals for ids aren't always guaranteed and it's not usually recommended to depend on them.
You can instead access any named form items from the <form> and vice versa.
<input type="button" onclick="calcgrade(this.form)" ...>
function calcgrade(form){
var sum = parseInt(form.one.value) + parseInt(form.two.value) + parseInt(form.three.value) + parseInt(form.four.value);
form.grade.value = sum / 4;
}
Or, use getElementById() to find each specifically:
function calcgrade() {
var grade = document.getElementById('grade');
var one = document.getElementById('one');
// etc.
}

Using javascript to get a value from html input

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.

Java Script function not working?

I'm using this codes below but seems my setValue() method is not working. can someone point what is wrong with this codes?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script language="javascript">
function rand ( n )
{
document.getElementById("orderRefId").value = ( Math.floor ( Math.random ( ) * n + 1 ) );
}
function setValue(amount1)
{
myValue = amount1;
document.getElementById("amount").value = myValue;
}
</script>
</head>
<body onLoad="rand( 2000000 )">
<!--
Note: https://www.pesopay.com/b2c2/eng/payment/payForm.jsp for live payment URL
https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp for test payment URL
-->
<form method="POST" name="frmPayment" action="https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp">
<table>
<tbody>
<tr>
<td>Order Reference No. (your reference number for every transaction that has transpired):</td>
<td><input type="text" id="orderRefId" name="orderRef" value="Test-001"/></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" onLoad = "setValue()" name="amount" value=""/></td>
</tr>
<tr>
<td>Currency Code - "608" for Philippine Peso, "840" for US Dollar:</td>
<td><input type="text" name="currCode" value="608"/></td>
</tr>
<tr>
<td>Language:</td>
<td><input type="text" name="lang" value="E"/></td>
</tr>
<tr>
<td>Merchant ID (the merchant identification number that was issued to you - merchant IDs between test account and live account are not the same):</td>
<td><input type="text" name="merchantId" value="18056869"/></td>
</tr>
<tr>
<td>Redirect to a URL upon failed transaction:</td>
<td><input type="text" name="failUrl" value="http://www.yahoo.com?flag=failed"/></td>
</tr>
<tr>
<td>Redirect to a URL upon successful transaction:</td>
<td><input type="text" name="successUrl" value="http://www.google.com?flag=success"/></td>
</tr>
<tr>
<td>Redirect to a URL upon canceled transaction:</td>
<td><input type="text" name="cancelUrl" value="http://www.altavista.com?flag=cancel"/></td>
</tr>
<tr>
<td>Type of payment (normal sales or authorized i.e. hold payment):</td>
<td><input type="text" name="payType" value="N"/></td>
</tr>
<tr>
<td>Payment Method - Change to "ALL" for all the activated payment methods in the account, Change to "BancNet" for BancNet debit card payments only, Change to "GCASH" for GCash mobile payments only, Change to "CC" for credit card payments only:</td>
<td><input type="text" name="payMethod" value="ALL"/></td>
</tr>
<tr>
<td>Remark:</td>
<td><input type="text" name="remark" value="Asiapay Test"/></td>
</tr>
<!--<tr>
<td>Redirect:</td>
<td><input type="text" name="redirect" value="1"/></td>
</tr>-->
<tr>
<td></td>
</tr>
<input type="submit" value="Submit">
</tbody>
</table>
</form>
</body>
</html>
NOTE: the variable "amount1" is came from my android. and its not causing the problem because I'm using it in other codes.
I will be very thankful for any thoughts.
1.You don't have no DOMInputElement with id "amount". You need to change the html like this:
<input type="text" onLoad = "setValue()" name="amount" id="amount" value=""/>
Or the js like this:
function setValue(amount1)
{
myValue = amount1;
document.frmPayment.amount.value = myValue;
}
2.The second issue is that you cannot attach the onLoad event to input element. What you can do, is put the <script/> with setValue() call or change your <body> tag to:
<body onLoad="rand(200000);setValue();">
JavaScript is in the default settings disabled in the WebView. You need to activate it first.
YourWebView.getSettings().setJavaScriptEnabled(true);
You also need to correct your JavaScript. You call the function document.getElementById(...), but your input element has no Id but a name. So you need to call document.getElementsByName(...)[0].
function text() {
var dt = new Date();
dt.format("dd-mmm-yyyy");
var newdt = dt.getFullYear();
var tt = document.getElementById("ctl00_ContentPlaceHolder1_txtPolicyStartDate").value;
var dt2 = new Date.parseLocale(tt, 'dd-MMM-yyyy');
dt2.setFullYear(dt2.getFullYear() + 1);
dt2.setDate(dt2.getDate() - 1);
document.getElementById("ctl00_ContentPlaceHolder1_txtPolicyExpiryDate").value = dt2.format("dd-MMM-yyyy");
return dt2;
}

How to empty a textbox, textarea in jquery

var $contact_title = $('#contact_title').val();
var $contact_summary = $('#bbcode').val();
I retreive a text area and text field then I do this:
$contact_title.val('');
$contact_summary.val('');
Nnone of them get emptied
HTML:
<form action="" method="get">
<table border="0">
<tr>
<td valign="top">Title:</td>
<td>
<input name="title" type="text" style="width:710px" id="contact_title" />
</td>
</tr>
<tr>
<td valign="top">Message:</td>
<td>
<textarea name="request" cols="30" rows="20" id="bbcode"></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="right" >
<input name="send" type="button" onClick="clicked()" value="Send" />
</td>
</tr>
</table>
</form>
You should store the element in your variable and not the value.
So, your code should be:
var $contact_summary = $('#bbcode');
$contact_summary.val('');
Btw, it's a good practice to use unobtrusive javascript and bind your click event outside of your html markup:
$('button').click(function() { //clear inputs });
Your problem is because you are setting your variables to be the string values of the elements, rather than the jQuery objects containing the elements.
Try this:
var $contact_title = $('#contact_title');
var $contact_summary = $('#bbcode');
$contact_title.val('');
$contact_summary.val('');
Or alternatively;
$('#contact_title').val('');
$('#bbcode').val('');
Your variable ($contact_title) contains the text, not the actual DOM-element, from what I can tell. If you change it to
$('#contact_title').val('');
You'll be fine.
you have to use the same syntax that you used while getting the values from those filed.
try:
$('#contact_title').val('');
$('#bbcode').val('');
In js fiddle easier to write/read javascript code. Here is an answer.
http://jsfiddle.net/7RFYx/
jQuery(document).ready(function () {
var $contact_title = $('#contact_title');
var $contact_summary = $('#bbcode');
var $contact_summary_val = $contact_summary.val();
var $contact_title_val = $contact_title.val();
$contact_title.val('');
$contact_summary.val('');
});

Categories