How to replace function that works with id to classname - javascript

This is a continuation of my previous question (Multiple date selection events to assign a value to an input field) and made some progression. I managed to partially solve the issue, and this is working only for one when I am using the document.getElementById. I know as IDs must be different to work for both, and therefore I am trying to use ClassName. And here I got studk. I am struggling to make it work for the arrays using the ClassName. Any help will be highly appreciated. below is the one working for ID.
<table class='table' id="tb_actions">
<thead>
<tr>
<th class="text-center" > Due </th>
<th class="text-center" > Date Complete </th>
<th class="text-center" > Overdue </th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" name="dt_due[]" id="datedue" class="form-control" /></td>
<td><input type="date" name="dt_complete[]" id="datecomplete" class="form-control" /></td>
<td><input type="text" name="overdue[]" id="overdue" class="form-control" /></td>
</tr>
<tr>
<td><input type="date" name="dt_due[]" id="datedue" class="form-control" /></td>
<td><input type="date" name="dt_complete[]" id="datecomplete" class="datecomplete form-control" /></td>
<td><input type="text" name="overdue[]" id="overdue" class="form-control" /></td>
</tr>
</tbody>
</table>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const d1 = document.getElementById("datedue");
const d2 = document.getElementById("datecomplete");
const od = document.getElementById("overdue");
$("#datecomplete").on("change", function () {
var dd1 = new Date($('#datedue').val());
var dd2 = new Date($('#datecomplete').val());
document.getElementById("demo1").innerHTML = dd1
document.getElementById("demo2").innerHTML = dd2
if( dd2 > dd1){
od.value = 'Yes';
od.style.color = 'red'
} else {
od.value = 'No';
od.style.color = 'blue'
}
});
</script>

you can try this as below, fiddle
<table class='table' id="tb_actions">
<thead>
<tr>
<th class="text-center" > Due </th>
<th class="text-center" > Date Complete </th>
<th class="text-center" > Overdue </th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" name="dt_due[]" id="datedue" class="form-control" /></td>
<td><input type="date" name="dt_complete[]" id="datecomplete" class="form-control datecomplete" /></td>
<td><input type="text" name="overdue[]" id="overdue" class="form-control" /></td>
</tr>
<tr>
<td><input type="date" name="dt_due[]" id="datedue" class="form-control" /></td>
<td><input type="date" name="dt_complete[]" id="datecomplete" class="datecomplete form-control" /></td>
<td><input type="text" name="overdue[]" id="overdue" class="form-control" /></td>
</tr>
</tbody>
</table>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
$(".datecomplete").on("change", function () {
var parent = $(this).closest("tr");
var dd1 = new Date(parent.find('#datedue').val());
var dd2 = new Date(parent.find('#datecomplete').val());
var od = parent.find('#overdue');
document.getElementById("demo1").innerHTML = dd1
document.getElementById("demo2").innerHTML = dd2
if( dd2 > dd1){
$(od).val('Yes');
$(od).css('color', 'red')
} else {
$(od).val('No');
$(od).css('color', 'blue')
}
});
</script>

Related

how can i get table of values exist in a TD of a table use jquery?

i want when i check checkbox in table get array values check (NAME, FIRST NAME, SALAIRENET) in example below it gives me just SALAIRENET and give NaN a name for the line check, please help me.
he is my table
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
#if($salaries->count())
#foreach($salaries as $key => $salarie)
<tr id="tr_{{$salarie->id}}">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $salarie->matricule }}</td>
<td class="name">{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td class="salaireValue">{{ $salarie->salairenet }}</td>
<td><input type="text" name="nbreJ" class="form-control" value="{{$data['nbr']}}"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
#endforeach
#endif
</table>
he is my code jquery:
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.table').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var currentHtml = $(allChecked[i]).parent().siblings('.salaireValue')[0];
var currentHtml1 = $(allChecked[i]).parent().siblings('.name')[0];
var result = parseInt($(currentHtml)[0].innerText);
var result1 = parseInt($(currentHtml1)[0].innerText);
console.log(result);
console.log(result1);
}
});
});
</script>
It might be helpful to create functions to break up the work. Also you can use parseInt() but it must receive a String that represents an Integer, so "1000" versus "One Thousand".
Consider the following:
$(function() {
function checkToggleAll(c, v) {
$(".checkbox", c).each(function(i, el) {
$(el).prop("checked", v);
});
}
function checkAll(c) {
if ($(".checkbox:checked", c).length == $(".checkbox", c).length) {
$("#check_all").prop("checked", true);
} else {
$("#check_all").prop("checked", false);
}
}
function gatherData(c) {
var rows = {}
$(".checkbox:checked", c).each(function(i, el) {
var row = $(el).parent().parent();
rows[row.attr("id")] = {
Name: $(".first-name", row).text().trim(),
SurName: $(".sur-name", row).text().trim(),
SalaireValue: parseInt($(".salaireValue", row).text().trim())
};
});
return rows;
}
$("#check_all").change(function() {
checkToggleAll($("tbody"), $(this).prop("checked"));
console.log(gatherData($(".table tbody")));
});
$("tbody .checkbox").on("change", function() {
checkAll($(".table tbody"));
console.log(gatherData($(".table tbody")));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="mytable">
<thead>
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
</thead>
<tbody>
<tr id="tr_1">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="1"></td>
<td>1</td>
<td>1001</td>
<td class="name">Simpson, Homer</td>
<td class="salaireValue">60000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_2">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="2"></td>
<td>2</td>
<td>1002</td>
<td class="name">Leonard, Lenny</td>
<td class="salaireValue">40000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_3">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="3"></td>
<td>3</td>
<td>1002</td>
<td class="name">Carlson, Carl</td>
<td class="salaireValue">55000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
</tbody>
</table>
I assume that the table content might get updated dynamically, so I am using .on() just in case. You can use .change() if needed.
Hope that helps.
A few changes in your for loop will make it:
for (var i = 0; i < allChecked.length; i++) {
var $tr = $(allChecked[i]).closest("tr");
var item = {
Name: $tr.find(".first-name").text(),
SurName: $tr.find(".sur-name").text(),
SalaireValue: $tr.find(".salaireValue").text()
};
console.log(item);
}
I've also separated the names into two spans in order to make it easy to select them.
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.table').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var $tr = $(allChecked[i]).closest("tr");
var item = {
Name: $tr.find(".first-name").text(),
SurName: $tr.find(".sur-name").text(),
SalaireValue: $tr.find(".salaireValue").text()
};
console.log(item);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
<tr id="tr_1">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="1"></td>
<td>1</td>
<td>1</td>
<td class="name"><span class='first-name'>Name</span> <span class='sur-name'>Surname</span></td>
<td class="salaireValue">123</td>
<td><input type="text" name="nbreJ" class="form-control" value="1"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_2">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="2"></td>
<td>2</td>
<td>2</td>
<td class="name"><span class='first-name'>Name</span> <span class='sur-name'>Surname</span></td>
<td class="salaireValue">456</td>
<td><input type="text" name="nbreJ" class="form-control" value="1"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
</table>

Total sum of all multiplied values of textboxes

I want to multiply the textbox values and after multiplication sum of all answer values. Example:
SUM (NSP * Current Sales)
This program is working fine but when I change any value it adds the change not replace the values. It should replace the value of array.
And if possible, please minimize the code logic also. Thanks.
$(document).ready(function() {
var val1;
var val2;
var multi;
one();
second();
});
function one() {
$(document).on("change", ".qty1", function() {
var sumqty1 = 0;
sumqty1 += $(this).val();
val1 = sumqty1;
});
}
function second() {
$(document).on("change", ".qty2", function() {
var sumqty1 = 0;
var sumqty2 = 0;
sumqty1 += $(this).closest('tr').find('.qty1').val();
sumqty2 += $(this).val();
val1 = sumqty1;
val2 = sumqty2;
mul(val1, val2);
});
}
var arr = [];
function mul(a, b) {
var hh;
multi = a * b;
arr.push(multi);
var totalsum = 0;
for (var i in arr) {
var value = arr[i];
totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
$("#totalvalue").text(totalsum);
}
console.log(arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
You are continually adding new values into arr and there's a whole lot of shared mutable state going on here.
If there aren't that many rows in the table, you're best off just recalculating the whole total each time a value changes. Less risk of the data stepping on itself that way:
$(document).ready(function() {
$(document).on('change', '.qty1, .qty2', recalculate);
function getTotal() {
return $('#myTable tr')
.toArray()
.map($)
.map(function (row) {
return row.find('.qty1').val() * row.find('.qty2').val();
})
.filter(function (val) { return !Number.isNaN(val); })
.reduce(function (a, b) { return a + b; }, 0);
}
function recalculate() {
$("#totalvalue").text(getTotal());
}
});
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<table id="myTable" style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
</body>
</html>
Id say something like:
$(".qty1, .qty2").on("change", function(){
var qty2 = $(".qty2"),
total = 0;
$(".qty1").each(function(ind){
total += $(qty2[ind]).val() * $(this).val();
})
$("#totalvalue").text(total)
})
Added at the end of the document.
Edited a little
The way you have it right now, you're adding new elements to the array in the order they're created, which doesn't allow you to access them later to change them because they could be stored in any order.
The code below saves each value in the array based on the value of val1 so that each element has a designated place in the array. Because of that, you can update any of the values when they are changed, like so:
var arr = [];
function one() {
$(document).on("change", ".qty1", function() {
var sumqty1 = $(this).val();
});
}
function second() {
$(document).on("change", ".qty2", function() {
var val1 = $(this).closest('tr').find('.qty1').val();;
var val2 = $(this).val();
mul(val1, val2);
});
}
function mul(a, b) {
arr[a - 1] = a * b;
var totalsum = 0;
for (var i in arr) {
var value = arr[i];
totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
$("#totalvalue").text(totalsum);
}
console.log(arr);
}
$(document).ready(function() {
one();
second();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
I also took out some unnecessary code, including:
The hh declaration (since that variable isn't used) in your second() function
a couple of extraneous lines in your one() function
the multi variable
the sumqty1 and sumqty2 variables (you can just use val1 and val2)
Your val1 and val2 variables didn't need to be global, since you are only using them in one function and passing them as parameters to another.
You could also remove the one() function if you want, since those values seem to be static -- but I'm not sure if you allow that value to be changed in your original code.

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! :)

how can i clone a Table Row with a keydown input using "which"?

I'm trying to clone the last row of my table and append it to the table, with blank values, when you press tab on the last name input field. so I wrote the code below. it works great until you get to the second line, it doesn't seem to clone and append the row if it's a clone. is there a way around this / What am I doing wrong?
$(document).ready(function() {
var $last_name = $('.last_name');
var $blank_row = $('tr:last');
var $time_table = $('#time_table');
$last_name.keydown(function(e) {
if (e.which === 9) {
$blank_row.clone().find('input').val('').end().appendTo($time_table);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="time_table">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Rate</th>
<th class="time">ST</th>
<th class="time">TH</th>
<th class="time">DT</th>
<th class="time">EX-ST</th>
<th class="time">EX-TH</th>
<th class="time">EX-DT</th>
</tr>
<tr class="blank_row">
<td><input type="text" name="last_name" class="last_name"></td>
<td><input type="text" name="first_name"></td>
<td><input type="text" name="rate"></td>
<td><input type="number" name="st" class="time_input"></td>
<td><input type="number" name="th" class="time_input"></td>
<td><input type="number" name="dt" class="time_input"></td>
<td><input type="number" name="ex_st" class="time_input"></td>
<td><input type="number" name="ex_th" class="time_input"></td>
<td><input type="number" name="ex_dt" class="time_input"></td>
</tr>
</table>
Because .last_name is added dynamically — variable $last_name stores a reference to the first empty row.
https://api.jquery.com/on/
$(document).ready(function() {
var $time_table = $('#time_table');
$time_table.on('keydown', '.last_name', function(e) {
if (e.which === 9) {
$('tr:last').clone().find('input').val('').end().appendTo($time_table);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="time_table">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Rate</th>
<th class="time">ST</th>
<th class="time">TH</th>
<th class="time">DT</th>
<th class="time">EX-ST</th>
<th class="time">EX-TH</th>
<th class="time">EX-DT</th>
</tr>
<tr class="blank_row">
<td><input type="text" name="last_name" class="last_name"></td>
<td><input type="text" name="first_name"></td>
<td><input type="text" name="rate"></td>
<td><input type="number" name="st" class="time_input"></td>
<td><input type="number" name="th" class="time_input"></td>
<td><input type="number" name="dt" class="time_input"></td>
<td><input type="number" name="ex_st" class="time_input"></td>
<td><input type="number" name="ex_th" class="time_input"></td>
<td><input type="number" name="ex_dt" class="time_input"></td>
</tr>
</table>
Try this:
The keydown() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created dynamically. To do that, need to create a "delegated" binding by using on().
$(document).ready(function () {
var $last_name = 'input.last_name';
var $blank_row = $('tr:last');
var $time_table = $('#time_table');
$("#time_table").on("keydown", $last_name, function (e) {
if (e.which === 9) {
$blank_row.clone().find('input').val('').end().appendTo($time_table);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="time_table">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Rate</th>
<th class="time">ST</th>
<th class="time">TH</th>
<th class="time">DT</th>
<th class="time">EX-ST</th>
<th class="time">EX-TH</th>
<th class="time">EX-DT</th>
</tr>
<tr class="blank_row">
<td><input type="text" name="last_name" class="last_name"></td>
<td><input type="text" name="first_name"></td>
<td><input type="text" name="rate"></td>
<td><input type="number" name="st" class="time_input"></td>
<td><input type="number" name="th" class="time_input"></td>
<td><input type="number" name="dt" class="time_input"></td>
<td><input type="number" name="ex_st" class="time_input"></td>
<td><input type="number" name="ex_th" class="time_input"></td>
<td><input type="number" name="ex_dt" class="time_input"></td>
</tr>
</table>

Using the same jQuery in multiple operations

I have a small question and I hope someone can help me with it :D
I’m trying to create a product table, in which a user just add the quantity of a product and the jquery makes the multiplication to its value and gives the result
I already made this, and it works well:
<script>
$(document).ready(function(){
$('#quantity_1').keyup(function(){
var price_1 = $("#price_1").val();
var quantity_1 = $("#quantity_1").val();
quantity_1 = quantity_1.replace(/[^0-9]+/g, '');
$("#quantity_1").val(quantity_1);
var total_1 = price_1 * quantity_1;
$( "#total_1" ).val( total_1.toFixed(2) );
});
});
</script>
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
</table>
Working demo here:
http://jsfiddle.net/EnterateNorte/9kswL0gf/
But I would like to be able to add more than one line, like so:
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Name 1</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
<tr>
<td>Name 5</td>
<td><input type="hidden" name="product[5][price]" id="price_5" value="10.00" />23.00</td>
<td><input type="text" name="product[5][quantity]" id="quantity_5" /></td>
<td><input type="text" name="product[5][total]" id="total_5" value="0" /></td>
</tr>
<tr>
<td>Name 3</td>
<td><input type="hidden" name="product[3][price]" id="price_3" value="130.00" />10.00</td>
<td><input type="text" name="product[3][quantity]" id="quantity_3" /></td>
<td><input type="text" name="product[3][total]" id="total_3" value="0" /></td>
</tr>
<tr>
<td>Name 4</td>
<td><input type="hidden" name="product[4][price]" id="price_4" value="12.00" />10.00</td>
<td><input type="text" name="product[4][quantity]" id="quantity_4" /></td>
<td><input type="text" name="product[4][total]" id="total_4" value="0" /></td>
</tr>
</table>
And if it isn’t to much trouble, I would be awesome if it would SUM all the totals and show a gran total at the end of the table :)
Use:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var price = $(this).parent().prev().find('input').val();
var quantity = $(this).val();
var total = price * quantity;
$(this).parent().next().find('input').val( total.toFixed(2) );
});});
Working Demo
Update: For showing Grand Total
var sum = 0;
//iterate through each textboxes and add the values
$('[name*=total]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseInt(this.value);
}
});
Working Demo
What you can do is to find the elements using their relative position instead of hard coded ids
$(document).ready(function () {
$('input[id^="quantity_"]').keyup(function () {
var $tr = $(this).closest('tr');
var price = $tr.find('input[id^="price_"]').val();
var quantity = this.value;
var total = (price * quantity) || 0;
$tr.find('input[id^="total_"]').val(total.toFixed(2));
});
});
Demo: Fiddle
I've updated your code in Fiddle. You need to change in your markup a bit.
<tr>
<td>Product Name</td>
<td><input type="hidden" class="price" ... />10</td>
<td><input type="text" class="quantity" ... /></td>
<td><input type="text" class="total" ... /></td>
</tr>
$(document).ready(function(){
$('.quantity').keyup(function(){
var parent = $(this).closest("tr");
var price = $(".price", parent).val();
var quantity = $(".quantity", parent).val();
var total = price * quantity;
$(".total", parent).val(total.toFixed(2));
});
});
I would recommend you to use common class
HTML:
<tr>
<td>Name 5</td>
<td>
<input type="hidden" class="price" value="10.00" />10.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
<tr>
<td>Name 3</td>
<td>
<input type="hidden" class="price" value="130.00" />130.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
Script:
$('.quantity').keyup(function () {
var tr = $(this).closest('tr');
var price = tr.find('.price').val();
var quantity = $(this).val();
var total = price * quantity;
tr.find('.total').val(total.toFixed(2));
});
DEMO
Modify your table:
<table border="1" cellpadding="5px" cellspacing="0" id='table' >
<!-- your rows with inputs -->
<tr>
<td>
<input id='totalSum' value='0' type='text' />
</td>
</tr>
</table>
Make all your 'total' inputs readonly by adding 'readonly' attribute.
js code:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var total = 0;
$('#table tr').each(function(i,item){
var price = parseFloat($(item).find('[name*=price]').val().replace(',','.'));
var quantity = parseInt($(item).find('[name*=quantity]').val());
if(!isNaN(price) && !isNan(quantity)){
total += price*quantity;
}
});
$("#totalSum").val(total.toFixed(2));
});
});

Categories

Resources