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.
Related
First of, I would like to say Thank you to those who started this field- Web Development. It is awesome especially coding. I think it is cool. Well, I am civil engineer by profession but does coding as my hobby free time. Now I got into seriousness and thought to improve my productivity in work as well as my team.
I have developed the table. I got the answer for calculating the "Amount" on the 7th column by multiplying the inputs of column 5 & 6 which is awesome (Sorry, I get too excited when i find the solution).
But where got stuck is the (got me frustrated! despite trying numerous times and finding other solutions or methods- this is what i got close to)- Total Sum of 7th column and 3rd Row. Total says 'Nan' which is odd. I am sure, i got somewhere wrong. I am unable to get the Total Sum of the rows in the Amount column.
Thank you for your patience in reading my question. Your help/comment/suggestions would be much appreciated. Any improvements are most welcome.
Please visit my fiddle site https://jsfiddle.net/sandz/bxj38zps/1/ which leads to the code that I had developed. or have a look below
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<title>TABLE RETEST</title>
</head>
<body>
<div class="w3-container w3-padding-4x w3-indigo">
<h2>
Table Testing
</h2>
</div>
<div class="w3-container w3-section w3-pale-green">
<table class="w3-table-all" id="sum_table" width="300" border="1">
<tr class="titlerow">
<th>SN</th>
<th>DESCRIPTION</th>
<TH>UNIT</TH>
<TH>REQD QTY</TH>
<TH>AVAIL. QTY</TH>
<TH>RATE</TH>
<TH>AMOUNT</TH>
<TH>REMARKS IF ANY</TH>
</tr>
<tr>
<td>1</td>
<td>Steel</td>
<td>Ton</td>
<td>200</td>
<td><input id="a.qty" type="number" oninput="calculate()" /></td>
<td><input id="rate" type="number" oninput="calculate()" /></td>
<td class="rowDataSd"><input id="amt1" type="number" name="amount" /></td>
<td><input type="text" name=""></td>
</tr>
<tr>
<td>2</td>
<td>Cement</td>
<td>Bags</td>
<td>300</td>
<td><input id="qty2" type="number" oninput="calculate1()" /></td>
<td><input id="rate2" type="number" oninput="calculate1()" /></td>
<td class="rowDataSd"><input id="amt2" type="number" name="amount" /></td>
<td><input type="text" name=""></td>
</tr>
<tr class="totalColumn">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="totalCol"><input type="button" onclick="Calculate()" value="calculate"> TOTAL:</td>
<td><input type="text" name=""></td>
</tr>
</table>
<script>
function calculate(){
var x1 = document.getElementById('a.qty').value;
var x2 = document.getElementById('rate').value;
var x3 = document.getElementById('amt1').value;
var x4 = x1 * x2;
amt1.value = x4;
}
function calculate1() {
var y1 = document.getElementById('qty2').value;
var y2 = document.getElementById('rate2').value;
var y3 = document.getElementById('amt2').value;
var y4 = y1 * y2;
amt2.value = y4;
}
var totals = [0];
$(document).ready(function() {
var $dataRows = $("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i) {
totals[i] += parseInt($(this).html());
});
});
$("#sum_table td.totalCol").each(function(i) {
$(this).html("total:" + totals[i]);
});
});
</script>
</div>
</body>
</html>
That is because in
$(this).find('.rowDataSd').each(function(i) {
totals[i] += parseInt($(this).html());
});
$(this).html() will return the input-field in the table cell and not the value within the input-field. Modify this bit to iterate over the input fields and get their value.
// ".rowDataSd input" selects all inputs within elements that have class="rowDataSd"
$(this).find('.rowDataSd input').each(function(i) {
// So "this" is now an input, so we can $(this).val() to get its value.
// And in case there is no value, parseInt will return NaN, so we default to 0 in this case
totals[i] += parseInt($(this).val()) || 0;
});
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
I have the following form that is created on the fly using Coldfusion. The different inputs all have different values when loaded, but share the same class.
I will have another input field with a unique identifier - #permup
The form is as follows (form tag stripped):
<table width="100%" border="0" cellpadding="0" cellspacing="0" id="county-table" style="margin-top: 15px;">
<tr>
<TD>Length</TD>
<TD align="center">PerM</TD>
</tr>
<tr bgcolor="#ffffff">
<TD>from 1-10m</TD>
<TD align="center"><input class="perm" type="text" name="PerM1" value="1.60" size="6" /></TD>
</tr>
<tr bgcolor="#efefef">
<TD>from 11-20m</TD>
<TD align="center"><input class="perm" type="text" name="PerM2" value="1.10" size="6" /></TD>
</tr>
<tr bgcolor="#ffffff">
<TD>from 21-50m</TD>
<TD align="center"><input class="perm" type="text" name="PerM3" value="1.50" size="6" /></TD>
</tr>
<tr bgcolor="#efefef">
<TD>from 51-80m</TD>
<TD align="center"><input class="perm" type="text" name="PerM4" value="1.55" size="6" /></TD>
</tr>
<tr bgcolor="#ffffff">
<TD>from 81-150m</TD>
<TD align="center"><input class="perm" type="text" name="PerM5" value="1.10" size="6" /></TD>
</tr>
<tr bgcolor="#efefef">
<TD>from 151-200m</TD>
<TD align="center"><input class="perm" type="text" name="PerM6" value="1.10" size="6" /></TD>
</tr>
<tr>
<td> </td>
<td><input id="permup" type="text" name="permup" value="0" size="6" /></td>
</tr>
</table>
What I need is that when someone types the base rate increase in the #permup field, the fields with the class .perm have all their values increased by that amount, and if someone then sets the #permup field to 0 (zero) the fields with .perm are set back to their original value.
This has to work with JQuery on the class name as the table rows could be any number. I have the following script:
<script language="JavaScript" type="text/javascript">
$('#permup').keyup( function() {
$('.perm').each(function(){
var defaultValue = $(this).val();
$(this).val( $('#permup').val() * defaultValue );
});
});
</script>
It kind of works, but sets every value the same in the .perm fields and also does weird stuff when the field #perm is clicked out of or set to zero.
I hope someone can help!!
Many thanks
JS
As others have said you need to make sure you are doing math with numbers and not the default "value" given by the .value property. Also it is not advisable to store values in your display as you run into issues on how to retrieve an old value once you modify it. Below is code that does what you want and keeps track of the original values.
<script language="JavaScript" type="text/javascript">
// Store default values
var perm_items = document.getElementsByClassName("perm");
var orig_perm_values = new Array(perm_items.length);
for (var i = perm_items.length - 1; i >= 0; i--)
{
orig_perm_values[i] = perm_items[i].value;
document.getElementById('out').innerHTML = orig_perm_values[i];
}
function updateValues(event)
{
for (var i = perm_items.length - 1; i >= 0; i--)
{
perm_items[i].value = (parseFloat(orig_perm_values[i]) + parseFloat(event.target.value)).toFixed(2);
}
}
</script>
Try using parseFloat() and use keyup and focus event as shown :-
$('#permup').on('keyup focus', function() {
$('.perm').each(function(){
var defaultval = $('#permup').val();
var myValue;
if(defaultval == "0"){
myValue = $(this).attr('value')
}
else{
myValue = parseFloat( parseFloat($(this).attr('value')) * parseFloat(defaultval) ) || $(this).attr('value')
}
$(this).val( myValue );
});
});
DEMO
Side Note :- Always try to use parseInt() or parseFloat() while dealing in numbers in javascript/jquery otherwise numbers are also treated as string.
I currently have this piece of code, which is to determine a height and wingspan from a given length. I'd really like for the results to be input as a measurement of feet and inches, and the resulting wingspan and height to respond in the same measurements. I don't mind if it uses apostrophises or periods.
<SCRIPT LANGUAGE="LiveScript">
function wings(form) {
form.wingspan.value = (form.length.value * .75) * 2
form.height.value = form.length.value * .5
}
</SCRIPT>
<TABLE>
<TR>
<TD>Dragon Length:</TD>
<TD><INPUT TYPE="text" NAME="length" SIZE=15 /></TD>
</TR>
<TR>
<TD>Dragon Wingspan:</TD>
<TD><INPUT TYPE="text" NAME="wingspan" SIZE=15 /></TD>
</TR>
<TR>
<TD>Dragon Height:</TD>
<TD><INPUT TYPE="text" NAME="height" SIZE=15 /></TD>
</TR>
<TR>
<TD><INPUT TYPE="button" VALUE="Calculate" ONCLICK="wings(this.form)" /></TD>
</TR>
</TABLE>
</FORM>
Are you loading this in your browser?
If you are, then LiveScript will not run in most cases. You probably want to look at programming using Javascript or JQuery instead.
Here's a snippet to get you started, with inline comments for explanation. Note I don't actually calculate anything for you... you should try doing that on your own as practice:
<!DOCTYPE html>
<html>
<head>
<!-- You need this line so you can load the JQuery functions that you will be using -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form id="wings">
<TABLE>
<TR><TD>Dragon Length:</TD><TD>
<INPUT TYPE ="text" id="winglength" SIZE=15</TD></TR>
</TABLE>
</form>
<!-- ID of this element is called "trigger" and will be used for clicking -->
<div id="trigger">Click me to calculate the Wingspan and Height!</div>
<!-- This div tag is called "wingspan" -->
<div id="wingspan">Wingspan is: </div>
<!-- Can you write the HTML code for "height" here? -->
<script>
// Everything in here will run when your page is loaded
$(document).ready(function() {
// When you click on the DIV tag called "trigger", you run this cod below.
$("#trigger").click(function() {
// "append" the wing length to the HTML tag above: the # refers to id called winglength
$("#wingspan").append($("#winglength").val());
// How you calculate the "height" is left as an exercise for the original poaster!
});
});
</script>
</body>
</html>
With no plugins or libraries, here is your example working...
Take a look at this example: http://jsfiddle.net/BtC4K/
Javascript:
function wings(){
var lenght = document.getElementsByName("length")[0];
var wingspan = document.getElementsByName("wingspan")[0];
var height = document.getElementsByName("height")[0];
wingspan.value = (lenght.value * 0.75) * 2;
height.value = lenght.value * 0.5;
}
HTML:
<table>
<tr>
<td>Dragon Length:</td>
<td><input type="text" name="length" SIZE=15 /></td>
</tr>
<tr>
<td>Dragon Wingspan:</td>
<td><input type="text" name="wingspan" SIZE=15 readonly /></td>
</tr>
<tr>
<td>Dragon Height:</td>
<td><input type="text" name="height" SIZE=15 readonly /></td>
</tr>
<tr>
<td><button onclick="wings()">Calculate</button></td>
</tr>
</table>
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;
}