I have wrote a code to split the input into two variables i.e. year and month. But, I am unable to make it work. It does not return the total number of months into the respective text field. Please help me debug my code.
$(function() {
$("#duration").keyup(function() {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0];
var months = fields[1];
var result = years.val() * 12 + months.val();
document.getElementById("totalNumMonths").innerHTML = result;
});
});
<html>
<body>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br/>
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" />
</td>
</tr>
</table>
</body>
</html>
Issues with code that I identified and fixed.
You dont need to access years.val() and months.val() because years and months holds string value.
If your input doesnot have a dot, the value for months will be undefined, so you can define years and months as fields[0] || "0" and fields[1] || "0" respectiveley.
Since element with id totalNumMonths is an input. You should set the value and not innerHTML
Since the years and months value produces a string, I have added a + symbol infront of them while setting the value for #totalNumMonths to convert them to number, since we are performing numiric action. Else + symbol on string will perform string concatenation.
Working Fiddle
$(function () {
$("#duration").keyup(function () {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0] || "0";
var months = fields[1] || "0";
var result = +years * 12 + +months;
document.getElementById("totalNumMonths").value = result;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br />
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" />
</td>
</tr>
</table>
You were calling val on string elements, which caused errors. And the result was adding months as a string value.
$(function () {
$("#duration").keyup(function () {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = parseInt(fields[0]);
var months = parseInt(fields[1]);
var result = (years * 12) + months;
document.getElementById("totalNumMonths").value = result;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number"/>
<br/>
<label>Total Months</label>
<input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number"/>
</td>
</tr>
</table>
</body>
</html>
In the code snippet, you are having the value of years & months in the respective variables, so you don't need to use years.val() to get that value.
Check this out!!
$(function() {
$("#duration").keyup(function() {
var input = document.getElementById('duration').value;
var fields = input.split('.');
var years = fields[0];
var months = fields[1] || 0;
var result = years * 12 + months;
document.getElementById("totalNumMonths").innerHTML = result;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Calculate Months</td>
<td>
<label>Input Years in the format (year.month e.g. 11.6)</label>
<input class="form-control" name="duration" id="duration" value="" type="number" />
<br/>
<label>Total Months :</label>
<!-- <input class="form-control" name="totalNumMonths" id="totalNumMonths" value="" type="number" /> -->
<span id="totalNumMonths">0</span>
</td>
</tr>
</table>
Related
I have a problem in automatically calculating the amount to be paid in a html table.
The html code looks like this:
<td>
<input type="hidden" id="getAvailability" readonly class="form-control input-sm" />
<strong>Qty</strong><br />
<input type="text" tabindex="1" name="Qty" id="getQty" class="form-control input-sm NumbersOnly" />
</td>
<td>
<strong>Rate</strong><br />
<input type="text" name="Rate" id="getRate" readonly class="form-control input-sm " />
</td>
<td>
<strong>Amount</strong><br />
<input type="text" name="Amount" id="getAmount" readonly class="form-control input-sm " />
</td>
Bellow this table i have another table with SQL entries, from where i select a row. On clicking a row from this table the following function is called:
$(function () {
$('#getStockID').val($.trim(cells[0].innerHTML));
$('#getItem').val($.trim(cells[1].innerHTML));
$('#getAvailability').val($.trim(cells[3].innerHTML));
$('#getRate').val($.trim(cells[4].innerHTML));
});
When i enter the quantity in first table i would like to have to amount to be paid calculated:
$('#getQty').keyup(function () {
var available = Number($('#getAvailability').val());
var quantity = Number($('#getQty').val());
var rate = Number($('#getRate').val());
if (quantity > available) {
$('#getQty').val(available);
quantity = available;
}
var amount = (quantity * rate);
$("#getAmount").val(amount.toFixed(2));
});
Using this code, i get NaN in the cell.
Please advice, i spent way too many hours on this issue, and i'm out of ideas.
Thank you very much!
If anyone text box has empty value this problem will occur.So that you have to use isNaN in javascript.
$('#getQty').keyup(function () {
var available = chkIsNaN(Number($('#getAvailability').val()));
var quantity = chkIsNaN(Number($('#getQty').val()));
var rate = chkIsNaN(Number($('#getRate').val()));
if (quantity > available) {
$('#getQty').val(available);
quantity = available;
}
var amount = (quantity * rate);
$("#getAmount").val(amount.toFixed(2));
});
function chkIsNaN(val){
if(isNaN(val)){
return '';
}
else{
return val;
}
}
sir
i have 7 text boxes .1st two take values from user and display the multiplication result on 3rd text box when it clicked.4th and 5th textboxes also take values and display the multiplication result in 6th text box when it clicked.now 7th textbox will display the addition result when it clicked.7th textbox takes the values from 3rd and 6th textbox.
my problem is that i can not do the addition and cant display the result in 7th text box in html and jscript.plz help me.....i am attached the code...
<html>
<script>
function getText1(){
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var tot1=parseInt(in1)*parseInt(in2);
document.getElementById('tot1').value=tot1;
}
function getText2(){
var in1=document.getElementById('in3').value;
var in2=document.getElementById('in4').value;
var tot2=parseInt(in1)*parseInt(in2);
document.getElementById('tot2').value=tot2;
}
function gt1(){
var in1=document.getElementById('tot1').value;
var in2=document.getElementById('tot2').value;
var gt1=parseInt(in1)+parseInt(in2);
document.getElementById('gt').value = gt1;
</script>
<form>
<input type="text"id="in1"/>
<input type="text" id="in2"/>
<input type="text" onclick="getText1()" id="tot1"/>
<br>
<input type="text"id="in3"/>
<input type="text" id="in4"/>
<input type="text" onclick="getText2()" id="tot2"/>
<br>
<input type="text" onclick="gt1()" id="gt1"/>
</form>
</html>
<html>
<script>
function getText1(){
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var tot1=parseInt(in1)*parseInt(in2);
document.getElementById('tot1').value=tot1;
}
function getText2(){
var in1=document.getElementById('in3').value;
var in2=document.getElementById('in4').value;
var tot2=parseInt(in1)*parseInt(in2);
document.getElementById('tot2').value=tot2;
}
function gt(){
var in1=document.getElementById('tot1').value;
var in2=document.getElementById('tot2').value;
var gt1=parseInt(in1)+parseInt(in2);
document.getElementById('gt1').value = gt1;
}
</script>
<form>
<input type="text"id="in1"/>
<input type="text" id="in2"/>
<input type="text" onclick="getText1()" id="tot1"/>
<br>
<input type="text"id="in3"/>
<input type="text" id="in4"/>
<input type="text" onclick="getText2()" id="tot2"/>
<br>
<input type="text" onclick="gt()" id="gt1"/>
</form>
</html>
use this code it is working. and compare with own code. thanks..
There are several problem
1). Element id is one line is incorrect. It should be:
document.getElementById('gt1').value = gt1;
2). result variable is undefined. It should be:
if (!isNaN(gt1))
3). onclick="gt1()" will not work (because there is id with the same name gt1). Use, for example:
function getText3() { ... }
and
<input type="text" onclick="getText3()" id="gt1"/>
Fiddle.
Update. Ok, I didn't notice that you want multiplication, but somewhy had written + in getText1() and getText2() functions. Then you should also replace these two + with *:
Multiplication fiddle.
You dont have element with id 'gt'.
Change last line of code to this:
document.getElementById('gt1').value = gt1;
You have not defined 'result' variable
and in 'gt1()' :
document.getElementById('gt').value = gt1;
1- There is no 'gt' element in the page
2- 'gt1' should renamed to 'result'
and at the end code will be:
<script language="javascript" type="text/javascript">
function getText1() {
var in1 = document.getElementById('in1').value;
var in2 = document.getElementById('in2').value;
var tot1 = parseInt(in1) + parseInt(in2);
document.getElementById('tot1').value = tot1;
}
function getText2() {
var in1 = document.getElementById('in3').value;
var in2 = document.getElementById('in4').value;
var tot2 = parseInt(in1) + parseInt(in2);
document.getElementById('tot2').value = tot2;
}
function gt1() {
var in1 = document.getElementById('tot1').value;
var in2 = document.getElementById('tot2').value;
var result = parseInt(in1) + parseInt(in2);
if (!isNaN(result)) {
document.getElementById('gt1').value = result;
}
//document.getElementById('gt1').value=gt1;
}
</script>
this is work properly.
Check the below code.
<script >
function getext3(){
txt1 = document.getElementById("text1").value;
txt2 = document.getElementById("text2").value;
document.getElementById("text3").value = parseInt(txt1)*parseInt(txt2);
}
function getext6(){
txt1 = document.getElementById("text4").value;
txt2 = document.getElementById("text5").value;
document.getElementById("text6").value = parseInt(txt1)*parseInt(txt2);
}
function getext7(){
txt1 = document.getElementById("text3").value;
txt2 = document.getElementById("text6").value;
document.getElementById("text7").value = parseInt(txt1)+parseInt(txt2);
}
</script>
Text1 : <input type="text" id="text1" value="5"> <br/>
Text2 : <input type="text" id="text2" value="2"> <br/>
Text3 : <input type="text" id="text3" value="" onclick="getext3()"> <br/>
Text4 : <input type="text" id="text4" value="7"> <br/>
Text5 : <input type="text" id="text5" value="10"> <br/>
Text6 : <input type="text" id="text6" value="" onclick="getext6()"> <br/>
Text7 : <input type="text" id="text7" value="" onclick="getext7()"> <br/>
I have been trying to write a function that finds the difference in two dates, and if the two dates are not 20 days or more apart an error message appears after the user clicks out of the form field. The code below is supposed to do this. However, seeing as I am really new to JavaScript I would greatly appreciate some help and/or advice as how to fix my problem.
`
<html>
<head><title>Form test page</title></head>
<body>
<link rel="stylesheet" type="text/css" href="OnbordingInStyle.css">
<script>
function dateerror() {
var c = 21;
var x = date ();
var y = document.getElementById('expected_start_date').value == "";
if ( x + c - y <= 0) {
datecrossover += "Attention this date is less than three weeks away, please be ready to expect delays with equipment for new employees \n";
}
if (datecrossover !="") {
alert(datecrossover);
return false;
}
}
</script>
<form method="post" action="Test.php" onsubmit="return dateerror()">
<table>
<tr>
<td>
<label for="expectedstartdate">Expected Start Date</label>
</td>
<td><div class="required">
<input type="date" name="expected_start_date" id="expected_start_date" size="15" maxlength="10" />*</div>
</td>
</tr>
<tr>
<td>
<input type="hidden" name="date_completed" id="date_completed" />
<script>
document.getElementById('date_completed').value = Date();
</script>
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="submit" />
<input type="reset" name="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
`
If you paste this into a new .html file - it should work :)
<link href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
$( "#datepicker2" ).datepicker();
});
</script>
<br><br><center>
<form action="" method="POST">
<input type="text" name="nowdate" id="datepicker" value="07/01/2014">
<input type="text" name="wantdate" id="datepicker2" value="07/31/2014">
<input type="submit" name="submitJS" id="submitJS" value="Submit" onclick="return ajaxSubmit();">
</form>
<script>
function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return (second-first)/(1000*60*60*24);
}
function ajaxSubmit() {
var date1 = $('#datepicker').val();
var date2 = $('#datepicker2').val();
//alert(date1 + " " + date2);
datediff = daydiff(parseDate($('#datepicker').val()), parseDate($('#datepicker2').val()));
if(datediff != 21) { alert("These dates are not 21 days apart"); }
return false;
}
</script>
This line
var y = document.getElementById('expected_start_date').value == "";
looks suspicious to me. It is setting y to 1 or 0 depending on whether the expected start date is set, but it seems from your question that what you really wanted was
var y = document.getElementById('expected_start_date').value;
You need to instantiate the date as a Date object. For example,
var x = new Date(Date.now());
That would set up a date with the current date and time. I'd recommend looking up the JavaScript reference at developer.Mozilla.com to learn more.
This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 9 years ago.
The old html and javascript code:
<tr>
<input id="pret_id_1" type="text" name="pret" />
<input id="val_id_1" type="text" name="val"/>
<input id="val_tva_id_1" type="text" name="val_tva"/>
<input id="cant_id_1" type="text" name="cant" />
</tr>
<script>
var x=document.form_factura;
x.val.value = (x.pret.value * x.cant.value).toFixed(2) ;
x.val_tva.value = ((x.pret.value * x.cant.value) * tva_val).toFixed(2);
if(!/^[a-z()+ A-Z()-]*$/.test(x.val_tva.value)){
var suma = (x.pret.value * x.cant.value)- (-x.val_tva.value);
} else {
var suma = (x.pret.value * x.cant.value);
}
x.suma.value = suma.toFixed(2);
...
</script>
I try to multiply this .. and I added arrays in the name elements .
<tr class="row1">
<input id="pret_id_1" type="text" name="pret[]" />
<input id="val_id_1" type="text" name="val[]"/>
<input id="val_tva_id_1" type="text" name="val_tva[]"/>
<input id="cant_id_1" type="text" name="cant[]" />
</tr>
<tr class="row2">
<input id="pret_id_2" type="text" name="pret[]" />
<input id="val_id_2" type="text" name="val[]"/>
<input id="val_tva_id_2" type="text" name="val_tva[]"/>
<input id="cant_id_1" type="text" name="cant[]" />
</tr>
How can I update the javascript code for array input name elements ??
if it's only one row (.row1) the javascript not working.. must be at least 2 elements with same name.
EDIT: I forgot to mention that I use php and mysql to store the data.
Thanks.
First you should not add the [] in the fields' names:
<tr class="row1">
<input id="pret_id_1" type="text" name="pret" />
<input id="val_id_1" type="text" name="val"/>
<input id="val_tva_id_1" type="text" name="val_tva"/>
<input id="cant_id_1" type="text" name="cant" />
</tr>
<tr class="row2">
<input id="pret_id_2" type="text" name="pret" />
<input id="val_id_2" type="text" name="val"/>
<input id="val_tva_id_2" type="text" name="val_tva"/>
<input id="cant_id_1" type="text" name="cant" />
</tr>
Then x.val will return an array of DOM elements (instead of one single element like before):
<script>
var x=document.form_factura;
for(var i=0; i<x.pret.length; i++) {
x.val[i].value = (x.pret[i].value * x.cant[i].value).toFixed(2) ;
x.val_tva[i].value = ((x.pret[i].value * x.cant[i].value) * tva_val).toFixed(2);
if(!/^[a-z()+ A-Z()-]*$/.test(x.val_tva.value)){
var suma = (x.pret[i].value * x.cant[i].value)- (-x.val_tva[i].value);
} else {
var suma = (x.pret[i].value * x.cant[i].value);
}
x.suma[i].value = suma.toFixed(2);
...
}
</script>
Well you have unique ids so you can loop
for(var i=1;i<=2;i++) {
var pret = document.getElementById("pret_id_" + i );
var cant = document.getElementById("cant_id_" + i );
var val = document.getElementById("val_id_" + i );
val.value = (pret.value * cant.value).toFixed(2) ;
}
if you want to do it by name,
var pretElems = document.form_factura["pret[]"];
var cantElems = document.form_factura["cant[]"];
var valElems = document.form_factura["val[]"]];
for(var i=1;i<=2;i++) {
var pret = pretElems[i];
var cant = cantElems[i];
var val = valElems[i];
val.value = (pret.value * cant.value).toFixed(2) ;
}
I have a jQuery function that calculates numbers from user inputs and outputs the result in a new readonly input. The code below shows the script I'm using, but the form is just for illustration purposes because the real form has 12 or more of these inputs. My questions is, is there a way to make my one script do all calculations for all the different inputs? Or, do I have to write out 12 or more of these scripts for each set?
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(':input').bind('keypress keydown keyup change',function(){
var pp_result = parseFloat($(':input[name="pp_month_result"]').val(),10),
pp_goal = parseFloat($(':input[name="pp_month_goal"]').val(),10);
var day = "<?php echo date('d'); ?>";
var monthDays = "<?php echo date('t'); ?>";
var v = '';
if (!isNaN(pp_result) && !isNaN(pp_goal)){
v = parseFloat((pp_result) / (day) * (monthDays) / (pp_goal) * 100).toFixed(0)+"%";
}
$(':input[name="pp_month_trend"]').val(v.toString());
});
});//]]>
</script>
</head>
<body>
<form>
Result 1 <input type="text" name="pp_month_result"><br>
Goal 1 <input type="text" name="pp_month_goal"><br>
Trend 1 <input type="text" name="pp_month_trend" readonly>
Result 2 <input type="text" name="aa_month_result"><br>
Goal 2 <input type="text" name="aa_month_goal"><br>
Trend 2 <input type="text" name="aa_month_trend" readonly>
</form>
</body>
<html>
The problem I did not clarify earlier is that the second set of inputs have different names so they can be posted to a separate PHP file.
<div>
<tr>
<td>POST</td>
<td>
<input type="text" name="pp_today_result" class="numbox">
</td>
<td>
<input type="text" name="pp_today_goal" class="numbox">
</td>
<td style="padding: 0 0 0 10px; border-left: 1px solid #D6D6D6;">
<input type="text" name="pp_month_result" class="numbox">
</td>
<td style="padding: 0 0 0 5px;">
<input type="text" name="pp_month_goal" class="numbox">
</td>
<td style="padding: 0 0 0 5px;">
<input type="text" name="pp_month_trend" class="numbox" readonly>
</td>
</tr>
</div>
My inputs are inside a table as show above, is this what's preventing the suggested solution from working for me?
Group the elements using a container so that you can find the related input elements easily
<form>
<div>
Result 1 <input type="text" name="pp_month_result"/><br/>
Goal 1 <input type="text" name="pp_month_goal"/><br/>
Trend 1 <input type="text" name="pp_month_trend" readonly />
</div>
<div>
Result 2 <input type="text" name="pp_month_result"/><br/>
Goal 2 <input type="text" name="pp_month_goal"/><br/>
Trend 2 <input type="text" name="pp_month_trend" readonly />
</div>
</form>
then
$(window).load(function(){
$(':input').bind('keypress keydown keyup change',function(){
var $div = $(this).closest('div');
var pp_result = parseFloat($div.find(':input[name$="_month_result"]').val(),10),
pp_goal = parseFloat($div.find(':input[name$="_month_goal"]').val(),10);
var day = 5;
var monthDays = 2;
var v = '';
if (!isNaN(pp_result) && !isNaN(pp_goal)){
v = parseFloat((pp_result) / (day) * (monthDays) / (pp_goal) * 100).toFixed(0)+"%";
}
$div.find(':input[name$="_month_trend"]').val(v.toString());
});
});
Demo: Fiddle