How to change multiple table rows' dates with one start date - javascript

Now, when a start date is selected in each row and click ok, an end date will display accordingly. So each table row has to manually click a button to show the end date.
Im wondering is it possible that if i only select one start date and click ok,
not only the first row end date is shown, but also 2nd , 3rd... etc rows' start date and end date will be automatically show accordingly to the interval days
PS: Please note that the number of rows are dynamic, coming from database and the total no of row is unknown.
Any ideas will be greatly appreciated. Thank you !!
(function($, window, document, undefined){
$(".addSkip").click(function() {
// row instance to use `find()` for the other input classes
var $row = $(this).closest('tr');
var date = new Date($row.find(".start_date").val()+" 0:00:00"),
days = parseInt($row.find(".days").val(), 10);
console.log(date.getDate());
console.log(days);
if (!isNaN(date.getTime())) {
date.setDate(date.getDate() + days);
$row.find(".end_date").val(date.toInputFormat());
} else {
alert("Invalid Date");
}
});
Date.prototype.toInputFormat = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
};
})
(jQuery, this, document);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<th>
start</th>
<th>end</th>
<th>interval</th>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<input type="button" size="10" value="ok" class="addSkip"></td>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"> </td>
</tr>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<input type="button" size="10" value="ok" class="addSkip"></td>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"> </td>
</tr>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<input type="button" size="10" value="ok" class="addSkip" ></td>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><input type="text" size="3" name="skip[]" class="days" value="10">
</tr>
</table>
desired result
start end interval
13/10/17 20/10/17 7
20/10/17 23/10/17 3
23/10/17 30/10/17 7
......
etc

I've removed the "ok" button in favour of a simpler change event (both on date_start and days) and added the logic for your need! if something is not clear, don't esitate to ask clarifications ;)
(function($, window, document, undefined){
$('input.start_date, input.days').on('change',function() {
var $row = $(this).closest('tr'),
$start = $row.find('.start_date'),
$end = $row.find('.end_date'),
$other = $row.find('.otherfield'),
$interval = $row.find('.days'),
date = new Date($start.val()+" 0:00:00"),
days = parseInt($interval.val(), 10);
console.log(date.getDate());
console.log(days);
if (!isNaN(date.getTime())) {
date.setDate(date.getDate() + days);
$end.val(date.toInputFormat());
$other.val(date.toInputFormat());
$row.next('tr')
.find('.start_date').val(date.toInputFormat()).trigger('change');
} else {
console.log("Invalid Date");
}
});
Date.prototype.toInputFormat = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
};
})
(jQuery, this, document);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>start</th>
<th>end</th>
<th>other</th>
<th>interval</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><textarea class="otherfield"></textarea></td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"> </td>
</tr>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><textarea class="otherfield"></textarea></td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"> </td>
</tr>
<tr>
<td><input type="date" size="15" name="date[]" class="start_date" \>
<td><input type="text" size="15" name="nextdate[]" class="end_date" \> </td>
<td><textarea class="otherfield"></textarea></td>
<td><input type="text" size="3" name="skip[]" class="days" value="10"></td>
</tr>
</tbody>
</table>

In jquery, you can do something like this to find multiple element:
$row.find("*[class^=".end_date"]")
For more details, refer jquery selectors

Related

How to get rid of the NaN/NaN/NaN

In the table, for the skips day column, the last row's default value will always be the word "last" which isn't a number. Now, the result date show "NaN/NaN/NaN",is there any way that i can replace that with sth like Nil.
Many thanks.
$('input.date, input.day').on('change', function () {
var $row = $(this).closest('tr');
var start = $row.find('.date').val();
if (start) {
var set = new Date(start);
set.setDate(set.getDate() + Number($row.find(".day").val()));
$row.find(".result").val([set.getMonth() + 1, set.getDate(), set.getFullYear()].join('/'));
var dt = set.getFullYear() + "-" + ("0" + (set.getMonth() + 1)).slice(-2) + "-" + ("0" + set.getDate()).slice(-2);
$row.next('tr').find('.date').attr('value', dt).trigger('change');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="one">
<th>Date</th>
<th>Skip days</th>
<th>Result</th>
<tbody>
<tr>
<td><input type="date" class="date"></td>
<td><input type="text" value="10" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
<tr>
<td><input type="date" class="date"></td>
<td><input type="text" value="15" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
<tr>
<td><input type="date" class="date"></td>
<td><input type="text" value="last" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
</tbody>
</table>
Here you go with a solution
$('input.date, input.day').on('change', function () {
var $row = $(this).closest('tr');
var start = $row.find('.date').val();
if (!isNaN($row.find(".day").val()) && start) {
var set = new Date(start);
set.setDate(set.getDate() + Number($row.find(".day").val()));
$row.find(".result").val([set.getMonth() + 1, set.getDate(), set.getFullYear()].join('/'));
var dt = set.getFullYear() + "-" + ("0" + (set.getMonth() + 1)).slice(-2) + "-" + ("0" + set.getDate()).slice(-2);
$row.next('tr').find('.date').attr('value', dt).trigger('change');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="one">
<th>Date</th>
<th>Skip days</th>
<th>Result</th>
<tbody>
<tr>
<td><input type="date" class="date"></td>
<td><input type="text" value="10" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
<tr>
<td><input type="date" class="date"></td>
<td><input type="text" value="15" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
<tr>
<td><input type="date" class="date"></td>
<td><input type="text" value="last" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
</tbody>
</table>
I've used iSNaN to check the input.day value
Hope this will help you.
You could always just manually update the last cell to overwrite the Nullvalue with something like: $("#one tbody tr:last-of-type .result")[0].value = 'Nil'.
This can be seen in the following example:
$('input.date, input.day').on('change', function() {
var $row = $(this).closest('tr');
var start = $row.find('.date').val();
if (start) {
var set = new Date(start);
set.setDate(set.getDate() + Number($row.find(".day").val()));
$row.find(".result").val([set.getMonth() + 1, set.getDate(),
set.getFullYear()
].join('/'));
var dt = set.getFullYear() + "-" + ("0" + (set.getMonth() +
1)).slice(-2) + "-" + ("0" + set.getDate()).slice(-2);
$row.next('tr').find('.date').attr('value', dt).trigger('change');
}
$("#one tbody tr:last-of-type .result")[0].value = 'Nil';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<table id="one">
<th>Date</th>
<th>Skip days</th>
<th>Result</th>
<tbody>
<tr>
<td>
<input type="date" class="date"></td>
<td><input type="text" value="10" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
<tr>
<td>
<input type="date" class="date"></td>
<td><input type="text" value="15" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
<tr>
<td>
<input type="date" class="date"></td>
<td><input type="text" value="last" class="day"> </td>
<td><input type="text" class="result"> </td>
</tr>
</tbody>
</table>
Hope this helps! :)

Re-Using JavaScript Function

Creating a cake ordering form, and the # of cakes available can vary from month to month. I am attempting to tweak a JS function created from #Anderson Contreira but in my fiddle it does not work. Here is what I have thus far - Why does nothing change when I enter a quantity?
https://jsfiddle.net/2uack1w6/
Syntax
JS
function calculate(el){
var quantity = el.val();
var id = el.attr("id").replace("item_","").replace("_qty","");
var data = {quantity: quantity,id:id};
var targetTax = $("#item_"+id+"_tax");
var targetTotalPrice = $("#item_"+id+"_totalprice");
$.post($.post(window.alert("It's been one or two or three entered");
});
}
var qty = $("#item_1_qty");
var qty1 = $("#item_2_qty");
var qty2 = $("#item_3_qty");
qty.on("keyup",function(){
window.alert("It's been one or two or three entered");
});
HTML/PHP
<body>
<form id="Form1" runat="server">
<div id="Form1" runat="server">
<table id="table1" border="1">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Tax</th>
<th>Total</th>
</tr>
<tr>
<td><label for="lblChoccake">Choc Cake</label></td>
<td><label for="lblitem1price">$25.00</label></td>
<td><input type="text" id="item_1_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_1_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_1_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
<tr>
<td><label for="lblLemonFudgecake">Lemon Fudge Cake</label></td>
<td><label for="lblitem2price">$15.00</label></td>
<td><input type="text" id="item_2_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_2_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_2_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
<tr>
<td><label for="lblCoconut">Coconut Cake</label></td>
<td><label for="lblitem3price">$35.00</label></td>
<td><input type="text" id="item_3_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_3_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_3_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
</table>
</div>
</form>
</body>
jQuery(function($) {
var qty = $("#item_1_qty");
var qty1 = $("#item_2_qty");
var qty2 = $("#item_3_qty");
qty.on("keyup",function(){
alert("It's been one or two or three entered");
});
});
Try this, you are assigning variables before the document has actually loaded.
Take a look here: https://jsfiddle.net/andersoncontreira/mtu6syby/1/
You can make some changes and will work well:
Add a class in each input of item_?_qty e.g.: <input type="text" id="item_1_qty" class="item_qty" />
In your javascript, you can leave the call generic:
jQuery(document).ready(function(){
//you can use a class for help you
$(".item_qty").on("keyup",function(){
//window.alert("It's been one or two or three entered");
calculate($(this));
});
});

Trouble with siblings

I'm trying to grab the value of sibling input fields in a form. The goal is to compare two date fields; the field that just changed and the other date field in that form. Each of the date fields is class "adate". I can get the value of teh current field but when I try to grab the other field in the sibling set, I get 'undefined' instead of the value of the field. Here's the javascript code:
$(".adate").change(function(){
var name = $(this).attr("name");
if (name == 'start') {
var start = new Date($(this).val());
var end = new Date($(this).siblings('[name="end"]').val());
} else {
var end = new Date($(this).val());
var sibs = $(this).siblings('.adate');
var start = new Date(sibs.eq(0).val());
}
if(end < start) alert("The end date must be after the start date.");
});
Here's the html:
<div class='jumbotron'>
<table>
<tr><td>Type</td><td>Start Date</td><td>End Date</td><td>By</td><td></td><td></td></tr><form action="manage.php" method="post">
<tr>
<td ><select name="type" class="form-control" style="width:auto;"><option value="hunt" selected >hunt</option><option value="closed" >closed</option><option value="snow" >snow</option></select></td><td><input type="date" name="start" value="2015-12-07" class="form-control adate" /></td>
<td><input type="date" name="end" value="2015-12-09" class="form-control adate" /></td>
<td><input type="text" name="uid" value="phil" class="form-control" readonly style="width:80px;" /></td>
<td><input type="hidden" name="id" value="1" /><button class="btn btn-sm btn-primary btn-block" type="submit">Save</button></td></form>
<td><form action="manage.php" method="post"><input type="hidden" name="id" value="1" /><input type="hidden" name="delete" value="delete" /><button class="btn btn-sm btn-primary btn-block" type="submit" style="background-color:red; " >Del</button></form></td>
</tr><form action="manage.php" method="post">
<tr>
<td><select name="type" class="form-control" style="width:auto;"><option value="hunt" >hunt</option><option value="closed" >closed</option><option value="snow" >snow</option></select></td>
<td><input type="date" name="start" class="form-control adate" value="2015-11-17" /></td>
<td><input type="date" name="end" class="form-control adate" /></td>
<td><input type="text" name="uid" value="phil" class="form-control" style="width:80px;" readonly/></td>
<td><button class="btn btn-sm btn-primary btn-block" type="submit">Add</button></form>
</tr>
</table>
</div>
What am I doing wrong??
Here is one way of doing it, assuming that you have only two distinctly named input fields. The advantage here is that the elements are picked out whether or not they are siblings.
$(".adate").change(function() {
var theRow = $(this).parents("tr");
/* theTag is for demo only, shows that the right row is picked out */
var theTag = theRow.attr('class');
alert(theTag);
var theStartDate = new Date($(theRow).find(".adate[name='startDate']").val());
var theEndDate = new Date($(theRow).find(".adate[name='endDate']").val());
if (theEndDate < theStartDate) {
alert("The end date must be after the start date.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr class="row1">
<td>
<input class="adate" type="text" name="startDate" value="2015-10-10">
</td>
<td>
<input class="adate" type="text" name="endDate" value="2015-10-10">
</td>
</tr>
<tr class="row2">
<td>
<input class="adate" type="text" name="startDate" value="2015-10-10">
</td>
<td>
<input class="adate" type="text" name="endDate" value="2015-10-10">
</td>
</tr>
</table>

jQuery- Dynamically multiply input values of table rows with different id

Dynamically adding table rows using below code. User ID is appended for input id.
var selResId = jQuery('#grid').jqGrid('getGridParam', 'selarrrow');
var j=1;
for (var i=0, il=selResId.length; i < il; i++) {
var name = jQuery('#grid').jqGrid('getCell', selResId[i], 'USER_NAME');
$('#addr'+j).html("<td style='text-align:center;'>"+name+"</td><td><input id='hours_"+selResId[i]+"' value='80' type='text' readonly /></td><td><input id='rate_"+selResId[i]+"' type='text' /></td><td><input name='markup_"+selResId[i]+"' type='text'/></td><td><input name='totalcost_"+selResId[i]+"' type='text' readonly></td>");
$('#resource_table').append('<tr id="addr'+(j+1)+'"></tr>');
j++;
}
}
HTML Generated
<tr id="addr1">
<td>John Doe</td>
<td><input type="text" readonly="" value="80" id="hours_10"></td>
<td><input type="text" value="" id="rate_10"></td>
<td><input type="text" value="" id="markup_10"></td>
<td><input type="text" readonly="" value="" id="totalcost_10"></td>
</tr>
<tr id="addr2">
<td>Foo User</td>
<td><input type="text" readonly="" value="80" id="hours_11"></td>
<td><input type="text" value="" id="rate_11"></td>
<td><input type="text" value="" id="markup_11"></td>
<td><input type="text" readonly="" value="" id="totalcost_11"></td>
</tr>
How do I multiply input values for hours, rate and markup and show it under total cost input using below formula. The event could be keyup.
Initially, totalcost = hours * rate
Case 1: If markup (%) > 0, for eg: 10%, then markup_cost = (hours * rate * markup) / 100
totalcost = (hours * rate) + markup_cost
Case 2: If markup (%) < 0, for eg: -10%, then markup_cost = (hours * rate * markup) / 100
totalcost = (hours * rate) - markup_cost
Try to use starts with selector like,
$(function(){
function setTotalCost(n){
var h=Number($('#hours_'+n).val()),
m=Number($('#markup_'+n).val()), // taking 0 if empty
r=Number($('#rate_'+n).val());
$('#totalcost_'+n).val(h*m*r);
}
$('[id^="rate_"]').on('keyup',function(){
var n = this.id.replace('rate_','');// get the number
setTotalCost(n);
});
$('[id^="markup_"]').on('keyup',function(){
var n = this.id.replace('markup_','');// get the number
setTotalCost(n);
});
});
$(function(){
function setTotalCost(n){
var h=Number($('#hours_'+n).val()),
m=Number($('#markup_'+n).val()), // taking 0 if empty
r=Number($('#rate_'+n).val());
$('#totalcost_'+n).val(h*m*r);
}
$('[id^="rate_"]').on('keyup',function(){
var n = this.id.replace('rate_','');// get the number
setTotalCost(n);
});
$('[id^="markup_"]').on('keyup',function(){
var n = this.id.replace('markup_','');// get the number
setTotalCost(n);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="addr1">
<td>John Doe</td>
<td>
<input type="text" readonly="" value="80" id="hours_10">
</td>
<td>
<input type="text" value="" id="rate_10">
</td>
<td>
<input type="text" value="" id="markup_10">
</td>
<td>
<input type="text" readonly="" value="" id="totalcost_10">
</td>
</tr>
<tr id="addr2">
<td>Foo User</td>
<td>
<input type="text" readonly="" value="80" id="hours_11">
</td>
<td>
<input type="text" value="" id="rate_11">
</td>
<td>
<input type="text" value="" id="markup_11">
</td>
<td>
<input type="text" readonly="" value="" id="totalcost_11">
</td>
</tr>
</table>

How to reflect a calculation from one field to another

I'm very new to JavaScript and I have an assignment that I'm unable to resolve. So I have a table with five fields and I need to calculate the total for a month, then automatically generate the yearly total in a different cell. I got to make the total work for the month but I have no idea how to reflect that in the year cells. Any help will be much appreciated. Thanks a lot for your time :)
Here's my code:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function update() {
var a = +document.forms['calc'].elements['fieldOne'].value,
b = +document.forms['calc'].elements['fieldTwo'].value,
c = +document.forms['calc'].elements['fieldThree'].value,
d = +document.forms['calc'].elements['fieldFour'].value,
e = +document.forms['calc'].elements['fieldFive'].value,
fieldTotal = ((b-d)*a)*c;
document.forms['calc'].elements['fieldTotal'].value = fieldTotal;
return false;
}
function update2() {
var f = +document.forms['calc'].elements['field6'].value,
g = +document.forms['calc'].elements['field7'].value,
h = +document.forms['calc'].elements['field8'].value,
i = +document.forms['calc'].elements['fieldFour'].value,
j = +document.forms['calc'].elements['fieldFive*12'].value,
field9=fieldFour;
field10=fieldFive*12;
fieldTotal2=fieldTotal*12;
document.write('fieldTotal2');
document.write('field9');
document.write('field10');
return false;
}
</script>
</head>
<body>
<form name="calc" action="#">
<table width="600" border="1">
<tr>
<td colspan="2"> </td>
<td width="63">Month</td>
<td width="109">Year</td>
</tr>
<tr>
<td colspan="2">Field1</td>
<td><input type="text" name="fieldOne" id="fieldOne" size="15" value="5,000" /></td>
<td><input type="text" name="field6" id="field6" size="15" value="60,000"/></td>
</tr>
<tr>
<td colspan="2">Field2</td>
<td><input type="text" name="fieldTwo" id="fieldTwo" value="3.0" size="15" /></td>
<td><input type="text" name="field7" id="field7" value="3.0" size="15" /></td>
</tr>
<tr>
<td colspan="2">Field3</td>
<td><input type="text" name="fieldThree" id="fieldThree" size="15" value="$350"/></td>
<td><input type="text" name="field8" id="field8" size="15" value="$350"/></td>
</tr>
<tr>
<td colspan="2">Field4</td>
<td><input type="text" name="fieldFour" id="fieldFour" value="1.5" size="15" /></td>
<td><input type="number" name="field9" id="field9" value="1.5" size="15" /></td>
</tr>
<tr>
<td colspan="2">Filed5</td>
<td><input type="text" name="fieldFive" id="fieldFive" size="15" value="75"/></td>
<td><input type="text" name="field10" id="field10" size="15" /></td>
</tr>
<tr>
<td width="137">Total</td>
<td width="83"><input type="button" value="Calculate" onClick="update();return false;" /></td>
<td><input type="text" name="fieldTotal" id="fieldTotal" size="15" readonly /></td>
<td><input type="text" name="fieldTotal2" id="fieldTotal2" size="15" readonly /></td>
</tr>
</table>
</form>
</body>
Based on what you described I think this should work for you.
Demo
function update() {
var frmEles = document.forms.calc.elements,
a = frmEles.fieldOne.value.replace(',',''), //Remove comma
b = frmEles.fieldTwo.value,
c = frmEles.fieldThree.value.replace('$',''), //Remove Dollar sign
d = frmEles.fieldFour.value,
e = frmEles.fieldFive.value,
fieldTotal = ((b-d)*a)*c;
//Total for the month
frmEles.fieldTotal.value = formatNumber(fieldTotal);
//Calculations for the year
frmEles.field6.value = formatNumber(a * 12);
frmEles.field7.value = formatNumber(b * 12);
frmEles.field8.value = '$' + formatNumber(c * 12); //Add back dollar sign
frmEles.field9.value = formatNumber(d * 12);
frmEles.field10.value = formatNumber(e * 12);
frmEles.fieldTotal2.value = formatNumber(fieldTotal * 12);
return false;
}
//Format the numbers with commas.
function formatNumber(n){
return n.toLocaleString();
}

Categories

Resources