Minor change required with this Javascript Code - javascript

So this is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body{font-family:Arial, Helvetica, sans-serif;font-size:12px;}
table{width:700px;margin:auto;border:solid 5px #cccccc}
table th{border-right:solid 1px #cccccc;border-bottom:solid 1px #000000;padding:5px;}
table th:last-child{border-right:0px;}
table td{border-right:solid 1px #d0d7e5;border-bottom:solid 1px #d0d7e5;}
table td:last-child{border-right:0px;}
table tr:last-child td{border-bottom:0px;}
table td input{padding:5px 0px;margin:auto;white-space:nowrap;overflow:hidden;outline:none;border:solid 1px #ffffff;text-align:center;width:99%;}
table td input.green{background:#00b050;border:solid 1px #00b050;}
table td input.red{background:#ff0000;border:solid 1px #ff0000;}
table td.active input{border:dotted 1px #333333;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
var row_template = "<tr><td><input type='text' value='0.00' maxlength='5' /></td><td><input type='text' value='0.00' maxlength='5' /></td><td><input type='text' value='0.00' maxlength='5' /></td></tr>";
var active_row;
var active_col;
// Initialize cell width
//$("table td").each(function()
//{
//var width = $(this).width();
//$(this).find("input").width(width-2);
//});
//----------------------
// Set Focus of cell
$("table").on("focus", "tr td input", function()
{
var row_count = $("table tr").size()-1;
$("table td").removeClass();
active_col = $(this).closest("td").index()+1;
active_row = $(this).closest("tr").index();
$(this).parent().addClass("active");
$(this).val("");
if(active_row == row_count)
{
$("table").append(row_template);
}
});
//------------------
// Set Blue of cell
$("table").on("blur", "tr td input", function(e)
{
var value = $(this).val();
if(isNaN(value) || value == "")
{
value = 0;
}
$(this).val(parseFloat(value).toFixed(2));
format_cell(active_row, active_col);
});
//-----------------
// Enter key on cell
$("table").on("keydown", "tr td input", function(e)
{
var value = $(this).val();
if(e.keyCode == 13)
{
$(this).blur();
if(active_col == 2)
{
$("table tr").eq(active_row).find("td").eq(active_col).find("input").focus();
}
else if(active_col == 3)
{
$("table tr").eq(active_row+1).find("td").eq(active_col-2).find("input").focus();
}
return(false);
}
else
{
if(value.length == 2)
{
$(this).val(value+".");
}
}
});
//------------------
// Download data
$("#btn_download").click(function()
{
var json = "";
var movement;
var pdi;
var ndi;
json += "[";
json += '{"movement":"Movement","pdi":"PDI","ndi":"NDI"},';
$("table tr:gt(0)").each(function(r)
{
movement = $(this).find("td").eq(0).find("input").val();
pdi = $(this).find("td").eq(1).find("input").val();
ndi = $(this).find("td").eq(2).find("input").val();
movement = (movement==0?"0":movement);
pdi = (pdi==0?"0":pdi);
ndi = (ndi==0?"0":ndi);
if(r==0)
{
json += '{"movement":"'+movement+'","pdi":"'+pdi+'","ndi":"'+ndi+'"}';
}
else
{
json += ',{"movement":"'+movement+'","pdi":"'+pdi+'","ndi":"'+ndi+'"}';
}
});
json += "]";
var csv = json_to_csv(json);
window.open("data:text/csv;charset=utf-8," + escape(csv));
});
//--------------
});
function format_cell(row, col, pre_value)
{
var pre_value = $("table tr").eq(row-1).find("td").eq(col-1).find("input").val();
var value = $("table tr").eq(row).find("td").eq(col-1).find("input").val();
if(col == 3)
{
if(parseFloat(value) < parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("red").addClass("green");
}
else if(parseFloat(value) > parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green").addClass("red");
}
else
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green red");
}
}
else
{
if(parseFloat(value) > parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("red").addClass("green");
}
else if(parseFloat(value) < parseFloat(pre_value))
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green").addClass("red");
}
else
{
$("table tr").eq(row).find("td").eq(col-1).addClass("active").find("input").removeClass("green red");
}
}
calculate_grid();
}
function calculate_grid()
{
$("table tr:gt(0)").each(function(r)
{
var pdi = $(this).find("td").eq(1).find("input").val();
var ndi = $(this).find("td").eq(2).find("input").val();
var movement = (parseFloat(pdi) - parseFloat(ndi)).toFixed(2);
r=r+1;
$(this).find("td").eq(0).find("input").val(movement);
if(movement > 0)
{
$(this).find("td").eq(0).find("input").removeClass("red").addClass("green");
}
else if(movement < 0)
{
$(this).find("td").eq(0).find("input").removeClass("green").addClass("red");
}
else
{
$(this).find("td").eq(0).find("input").removeClass("green red");
}
});
}
function json_to_csv(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = "";
var line = "";
if($("#labels").is(':checked'))
{
var head = array[0];
if($("#quote").is(':checked'))
{
for(var index in array[0])
{
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
}
else
{
for(var index in array[0])
{
line += index + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
for(var i=0;i<array.length;i++)
{
var line = "";
if ($("#quote").is(':checked'))
{
for (var index in array[i])
{
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
}
}
else
{
for(var index in array[i])
{
line += array[i][index] + ',';
}
}
line = line.slice(0, -1);
str += line + '\r\n';
}
return(str);
}
</script>
<title>Excel</title>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<th width="30%">Movement Data</th>
<th width="35%">PDI</th>
<th width="35%">NDI</th>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
<tr>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
<td><input type="text" value="0.00" maxlength="5" /></td>
</tr>
</table>
<center><input type="button" id="btn_download" value="Download" /></center>
</body>
</html>
I want to change color in the movement cell according to the data. If the the current value is lower than the preceding value I want it to be red and if the current value is more than the preceding value than I want it to be green. I believe it requires a minor change in the "movement function"
Please help.
Here is a jsfiddle for the scenario: Click Here

Is this not what already happens. I have tested the jsfiddle (http://jsfiddle.net/4QBwK/), behaviour seems a little odd, but I think it fits what you have specified.
The only change I think is needed is to remove most of the code from the format_cell() function that seems to randomly light up cells in either red or green. I have commented it out on this jsfiddle: http://jsfiddle.net/4QBwK/1/
So you would just have this instead:
function format_cell(row, col, pre_value)
{
calculate_grid();
}

Related

Get all values per table column dynamically using javascript or jquery

I need to get all values per column dynamically and save it using JS or Jquery. I have a photo here so that you guys can visualize what I am trying to do. Please see the image.
Sad to say this is as far as I can go. I cant seems to get what I realy want to achieve. Just a beginner here.
$(function() {
$('#add_supplier').click(function() {
$('#supplier_table > thead > tr#first-header').append(
'<th colspan="2" class="supplier_name"><input type="text" class="form-control" placeholder="Enter Supplier" style="text-align: center;"></th>'
);
$('#supplier_table > thead > tr#second-header').append(
'<th>Price</th>' +
'<th>Total</th>'
);
$('#supplier_table > tbody > tr').not('#totals,#tr-td-2').append(
'<td class="ignore"><input type="text" class="form-control price text-right" ></td>' +
'<td><input type="text" class="form-control total text-right" readonly></td>'
);
$('#supplier_table > tbody > #totals').not('#tr-td-2').append(
'<td class="ignore"><input class="form-control" disabled></td>' +
'<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>'
);
$('#supplier_table > tbody > #tr-td-2').append(
'<td colspan="2" style="width: 160px;"><input style="text-align: center;" class="form-control" type="text"></td>'
);
//
refresh_index();
//
});
$('#add_terms').click(function() {
var $tableBody = $('#supplier_table').find("tbody").not('#totals'),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
$trNew.find('input').val('');
$trLast.after($trNew);
refresh_index();
});
// $('#add_supplier').click();
$('#add_item').click(function() {
$('#supplier_table > tbody').not('#totals, #tr-td-2').append(
// $("#supplier_table tbody tr:last").clone()
'<tr class="tbody-tr">' +
'<td class="ignore"><input type="text" class="form-control " value="Monitor" readonly=""></td>' +
'<td class="ignore"><input type="text" class="form-control qty" value="30" readonly=""></td>' +
'<td class="ignore"><input type="text" class="form-control price"></td>' +
'<td><input type="text" class="form-control total for_sum-1" readonly=""></td>' +
'</tr>'
);
//
refresh_index();
//
});
//
function refresh_index() {
$('.price').each(function(i) {
i++;
$(this).attr('id', 'price-' + i);
$(this).attr('data-num', i);
event_handler();
});
$('.total').each(function(i) {
i++;
$(this).attr('id', 'total-' + i);
});
$('.qty').each(function(i) {
i++;
$(this).attr('id', 'qty-' + i);
});
$('.grandtotal').each(function(i) {
i++;
$(this).attr('id', 'grandtotal-' + i);
});
$('.supplier_name').each(function(i) {
i++;
$(this).attr('id', 'supplier_name-' + i);
});
}
refresh_index();
//
//
function event_handler() {
$('.price').unbind('keyup').bind('keyup', function() {
var id = this.id;
var num = id.split('-');
var pos = $(this).closest('tr').index() + 1;
var qty = $('#qty-' + pos).val();
var price = $(this).val();
var total = parseFloat(qty) * parseFloat(price);
if (isNaN(total)) {
var total = 0;
}
$('#total-' + num[1]).text(total);
$('#total-' + num[1]).val(total);
var num_of_supplier_name = $('.supplier_name').length;
sum_of_total();
});
}
function sum_of_total() {
// var sum = 0;
// //iterate through each textboxes and add the values
// $(".total").each(function () {
// //add only if the value is number
// if (!isNaN($(this).val()) && $(this).val().length != 0) {
// sum += parseFloat(this.value);
// }
// });
// //.toFixed() method will roundoff the final sum to 2 decimal places
// $("#grandtotal-"+num).val(sum);
var totals = [];
$('#tb').find('tr').each(function() {
var $row = $(this);
$row.children('td').not('.ignore').each(function(index) {
totals[index] = totals[index] || 0;
totals[index] += parseInt($(this).text()) || 0;
});
})
$('#totals td').not('.ignore').each(function(index) {
// $(this).text(totals[index]);
var id = index + 1;
$('#grandtotal-' + id).val(totals[index]);
});
$("#tb").on("click", "tr", function() {
$(this).find("td").slice(0, 4).prop("contenteditable", true);
});
// var max = 0;
// $('.grandtotal').each(function()
// {
// $this = parseInt( $(this).val() );
// // console.log($this);
// if ($this > max) {
// max = $this;
// }
// // $('.grandtotal').val(max).css('background-color','yellow');
// // console.log('Lowest Offer : '+max);
// });
// console.log('Lowest Offer : '+max);
// var high = Math.min.apply(Math, $('.grandtotal').map(function(){
// return $(this).val()
// }))
// console.log('Lowest Offer : '+high);
var vals = $('.grandtotal').map(function() {
return parseInt($(this).val(), 10) ? parseInt($(this).val(), 10) : null;
}).get();
// then find their minimum
var min = Math.min.apply(Math, vals);
console.log(min);
// tag any cell matching the min value
$('.grandtotal').filter(function() {
// return parseInt($(this).val(), 10) === min;
if (parseInt($(this).val(), 10) === min) {
$(this).css("background-color", "#dff0d8");
} else {
$(this).css("background-color", "transparent");
}
});
}
//
});
<button type="button" class="btn btn-success" id="add_supplier">Add Supplier</button>
<!-- <button type="button" class="btn btn-default" id="add_item">Add Item</button> -->
<button type="button" class="btn btn-primary" id="add_terms">Add Terms</button>
<table class="table table-bordered" id="supplier_table">
<thead>
<tr id="first-header">
<th></th>
<th></th>
<th colspan="2" class="supplier_name" id="supplier_name-1"><input type="text" class="form-control" placeholder="Enter Supplier" style="text-align: center;"></th>
</tr>
<tr id="second-header">
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="tb">
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control" value="Mouse" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="10" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control" value="Keyboard" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="20" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control " value="Monitor" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="30" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr id="totals">
<td class="ignore"></td>
<td class="ignore"></td>
<td class="ignore"><input class="form-control" disabled value="Grand Total : " style="text-align: right;"></td>
<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>
</tr>
<tr id="tr-td-2">
<td>
<p style="width: 60px;"></p>
</td>
<td><input style="font-weight: bold; text-align: right;" type="text" class="form-control" placeholder="Enter terms"></td>
<!-- <td ><p style="width: 60px;"></p></td> -->
<td colspan="2" style="width: 160px;"><input style="text-align: center;" class="form-control" type="text"></td>
</tr>
</tbody>
</table>
Actual Demo Link
JSFIDDLE

How to increment the two text box values when button is clicked?

jQuery(document).ready(function() {
// This button will increment the value
$('.qtyplus').click(function(e) {
e.preventDefault();
fieldName = $(this).attr('field');
//alert(fieldName);
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
if (!isNaN(currentVal)) {
$('input[name=' + fieldName + ']').val(currentVal + 1000);
} else {
$('input[name=' + fieldName + ']').val(1000);
}
});
});
function buttonClick() {
//alert("hi");
var n = document.getElementById('rs').value;
alert(n);
var i = 50;
if (i == 50) {
alert(i);
var n = +n + +i;
alert(n);
}
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<h3> Calculator</h3>
<table style="width: 30%;">
<form name="calc" action="" method="post">
<tr>
</tr>
<tr>
<td>quantity:</td>
<td><input type="text" name="value1" /></td>
</tr>
<tr>
<td>price:</td>
<td>
<input type='text' name='quantity' value='2000' class='qty' />
<input type='button' value='+' class='qtyplus' field='quantity' onclick="buttonClick()" />
</td>
</tr>
<tr>
<td>discount:</td>
<td><input type='text' name='rs' value='500' field='rs' id='rs' class='counter' onclick="buttonClick()" /></td>
</tr>
<tr>
</tr>
</form>
</table>
In above HTML code, when button is clicked, I have to increment the two text box values
For example, click a button, price text box value will be 3000, discount text box value will be 550
price text box value is incremented, but discount value will not be changed.
Second script are run,but the text box value are not changed.
You just forget to change the value of the discount input.
<script type="text/javascript">//second script
function buttonClick() {
//alert("hi");
var n = document.getElementById('rs').value;
alert(n);
var i = 50;
if (i == 50) {
alert(i);
var n = +n + +i;
alert(n);
$("#rs").val(n) // add this line
}
}
</script>
You have not written anything to change value of discount textbox.
you can do as follows:
$('.qtyplus').click(function (e) {
e.preventDefault();
qty = $('.qty').val();
discount = $('#rs').val();
var currentQtyVal = parseInt(qty);
if (!isNaN(currentQtyVal)) {
$('input[name=quantity]').val(currentQtyVal + 1000);
} else {
$('input[name=quantity]').val(1000);
}
var currentDiscountVal = parseInt(discount);
if (!isNaN(currentDiscountVal)) {
$('input[name=rs]').val(currentDiscountVal + 50);
} else {
$('input[name=rs]').val(50);
}
});

(CLOSED) When button is clicked, How to Get input values in the 1st table row and display them in the newly added rows

Now, when the ok button is clicked, additional rows will be added below the 1st table row. I'm wondering when the button is clicked,how to get the values from the 1st table row, and add those values to the row(s) newly added (possibly more than 1 row depends on how many row(s) user input.
Desired result
No Tommy Danvers
1 Tommy Danvers
2 Tommy Danvers
3 Tommy Danvers
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = ` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]"></td>
<td><input type="text" name="other[]"></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy"> </td>
<td><input type="text" name="other[]" value="Danver"> </td>
</tbody>
</table>
So i have found this will do what i need , it's likely there's gonna be better answer out there. If u have one, please do share. Thank you
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = ` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]" class="tommy"></td>
<td><input type="text" name="other[]" class="danver"></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
$("#add-row").on('click', function() {
var set = $('#tommy,#danver').val();
if (set) {
$('.tommy,.danver ').val(set);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy" id="tommy"> </td>
<td><input type="text" name="other[]" value="Danver" id="danver"> </td>
</tbody>
</table>
Here you go with the solution https://jsfiddle.net/r3rbkf72/1/
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
var name = $('table#one tbody td:eq(1) input[name="name[]"]').val();
var other = $('table#one tbody td:eq(2) input[name="other[]"]').val();
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = `<tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]" value=${name}></td>
<td><input type="text" name="other[]" value=${other}></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy"> </td>
<td><input type="text" name="other[]" value="Danver"> </td>
</tbody>
</table>
Below two lines of code I have added.
var name = $('table#one tbody td:eq(1) input[name="name[]"]').val();
var other = $('table#one tbody td:eq(2) input[name="other[]"]').val();
This will help you to receive the data from the top row textbox.

jQuery invoice and HTML

I am currently working on a dynamic invoice system for myself. But I can't seem to completely get it working correctly.
I have a invoice table like this in HTML:
Product name -- Quantity -- Tax -- Price (without tax) -- total price
My HTML looks like this:
<td><input type="text" placeholder="Item name" class="form-control" /></td>
<td class="text-center"><input type="number" min="1" id="target" placeholder="Quantity" class="form-control quantity" /></td>
<td class="text-center"><input type="text" placeholder="TAX" class="form-control tax" /></td>
<td class="text-right"><input type="text" placeholder="Price" class="form-control" /></td>
<td class="text-right"><input type="text" disabled placeholder="0,00" class="form-control price" /></td>
I can add rows with this Javascript code:
<script>
function addItem(){
var itemRow =
'<tr>' +
'<td><input type="text" class="form-control" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control" placeholder="Quantity" /></td>' +
'<td><input type="text" class="form-control tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control price" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table tr:last").after(itemRow);
}
</script>
And I calculate it with this jQuery code:
<script>
var total = 0;
var taxTotal = 0;
(function() {
$('#items_table').on('change', 'input', function() {
if( !$(this).hasClass('tax')) {
totalPrice = 0;
var row = $(this).closest('tr');
// ## Get quantity
var qty = parseFloat(row.find('input:eq(1)').val());
if (qty < 0) {
row.addClass('danger');
return;
} else {
row.removeClass('danger');
}
// ## Get the entered price
var price = parseFloat(row.find('input:eq(3)').val());
if (price < 0) {
row.addClass('danger');
return;
} else {
row.removeClass('danger');
}
// ## Calculate total price
var total = qty * price;
// ## Set total price at the end
row.find('input:eq(4)').val(isNaN(total) ? '' : total);
tax = parseFloat(row.find('input:eq(2)').val());
var salesTax = total * (tax / 100);
if (!isNaN(salesTax)) {
$('#tax-' + row.find('input:eq(2)').val()).html(salesTax.toFixed(2));
$('#tax_percentage').html(tax + '%');
$('#tax_total').html('€ ' + salesTax.toFixed(2));
$('.price').each(function (i, obj) {
// ## Add all the prices again
totalPrice = totalPrice += parseFloat($(this).val()) + salesTax;
});
}
$('#total_price').html('€ ' + totalPrice.toFixed(2));
}else{
// ## Remove all the taxes
$('[id^=tax-tr-]').remove();
if($('#tax-'+ $(this).val()).length > 0 ){
console.log('it already exists');
}else{
$('.tax').each(function (i, obj) {
var itemRow =
'<tr id="tax-tr-' + $(this).val() + '">' +
'<td colspan="4" class="font-w600 text-right">BTW ' + $(this).val() + '%</td>' +
'<td style="width: 20%;" class="text-right">€ <span id="tax-' + $(this).val() + '">0</span></td>' +
'</tr>';
$("#subtotal_table tr").eq(-2).after(itemRow);
});
}
}
});
})();
</script>
Although, its not exactly doing what I want. I want the total price to be at the end of the table row (total price disabled row)
And I want the tax to be added below the invoice (a new table), like this:
Sub total: (Total price without tax)
TAX 10%: (The tax ammount according to the 10%)
TAX 15%: (The tax ammount according to the 15%)
Total: (Sub total price + the tax prices)
But the problem I get is once I have 2 items in the table, and I change the first row's TAX, it gets all messed up.
I am currently out of idea's how to correctly do this. So I all I need is once I filled 1 item row, the tax gets in the total table added, and once I change that tax in that row, it changes below aswell, and the price has to be changed aswell.
Can someone get me back on the right track?
It's not exactly clear what you want to display in the second table,however, I believe the below will suite your needs.
Here is a jsFiddle as well
$('#addRow').click(function () {
addItem();
});
$('#items_table').on('keyup', '.update', function () {
var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
if( key == 8 || key == 46 ) return false;
calculateTotals();
});
$('#taxPercentage').change(function () {
calculateTotals(); // user changed tax percentage, recalculate everything
});
function calculateTotals(){
// get all of the various input typs from the rows
// each will be any array of elements
var nameElements = $('.row-name');
var quantityElements = $('.row-quantity');
var taxElements = $('.row-tax');
var priceElements = $('.row-price');
var totalElements = $('.row-total');
// get the bottom table elements
var taxPercentageElement =$('#taxPercentage');
var subTotalElement =$('#subTotal');
var totalTaxElement =$('#totalTax');
var grandTotalElement =$('#grandTotal');
var subTotal=0;
var taxTotal=0;
var grandTotal=0;
$(quantityElements).each(function(i,e){
// get all the elements for the current row
var nameElement = $('.row-name:eq(' + i + ')');
var quantityElement = $('.row-quantity:eq(' + i + ')');
var taxElement = $('.row-tax:eq(' + i + ')');
var priceElement = $('.row-price:eq(' + i + ')');
var totalElement = $('.row-total:eq(' + i + ')');
// get the needed values from this row
var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
qty = qty == '' ? 0 : qty; // if blank default to 0
quantityElement.val(qty); // set the value back, in case we had to remove soemthing
var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
price = price == '' ? 0 : price; // if blank default to 0
priceElement.val(price); // set the value back, in case we had to remove soemthing
// get/set row tax and total
// also add to our totals for later
var rowPrice = (price * 1000) * qty
subTotal = subTotal + rowPrice;
var tax = taxPercentageElement.val() * rowPrice;
taxElement.val((tax / 1000).toFixed(2));
taxTotal = taxTotal + tax;
var total = rowPrice + tax
totalElement.val((total / 1000).toFixed(2));
grandTotal = grandTotal + total;
});
// set the bottom table values
subTotalElement.val((subTotal / 1000).toFixed(2));
totalTaxElement.val((taxTotal / 1000).toFixed(2));
grandTotalElement.val((grandTotal / 1000).toFixed(2));
}
function addItem() {
var itemRow =
'<tr>' +
'<td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
'<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
'<td><input type="text" class="form-control update row-tax" placeholder="Tax" /></td>' +
'<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
'<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
'</tr>';
$("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
font-size:18px;
}
.myTable {
background-color:#ffaa56;
}
.myTable {
border-collapse: collapse;
border-spacing: 0;
width:100%;
height:100%;
margin:0px;
padding:0px;
}
.myTable tr:last-child td:last-child {
-moz-border-radius-bottomright:0px;
-webkit-border-bottom-right-radius:0px;
border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
-moz-border-radius-topleft:0px;
-webkit-border-top-left-radius:0px;
border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
-moz-border-radius-topright:0px;
-webkit-border-top-right-radius:0px;
border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
-moz-border-radius-bottomleft:0px;
-webkit-border-bottom-left-radius:0px;
border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
background-color:#ffffff;
}
#items_table tr:nth-child(even) {
background-color:#ffd0a3;
}
.myTable td {
vertical-align:middle;
border:1px solid #000000;
border-width:0px 1px 1px 0px;
text-align:left;
padding:7px;
font-size:10px;
font-family:Arial;
font-weight:normal;
color:#000000;
}
.myTable tr:last-child td {
border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
border-width:0px 0px 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
<thead>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="items_table"></tbody>
<tfoot>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Tax</th>
<th>Price</th>
<th>Total</th>
</tr>
</tfoot>
</table>
<br>
<br>
<table class="myTable" style="width:70%">
<thead>
<tr>
<th>Tax Percentage</th>
<th>Sub Total</th>
<th>Total Tax</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody id="items_table">
<tr>
<td>
<select name="" id="taxPercentage" class="form-control">
<option value=".10">10%</option>
<option value=".15">15%</option>
</select>
<td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
<td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
</tr>
</tbody>
<tfoot>
</tfoot>
</table>
<p>Add rows and give them values for quantity and price, the script will do the rest.</p>
<p>Select a diferent tax amount to recalculate everything</p>

Using arrows-keys to navigate and select text in input box

as explain on solution for the issue:
Using arrows-keys to navigate
http://jsfiddle.net/BdVB9/
I have same table with some text input, and I got some problem to select text in input box in tables cells during navigating between cells.
can any one help me to solve it? navigation works fine but not select text in input box!!! and also i want to navigate only between cells that have input-box, not all them
Notes: I just want to navigate between cells that have text input-box.
table codes:
<table border="1" id="navigate">
<tbody>
<tr>
<td><input type="text" id="1" class="input"></td>
<td></td>
<td><input type="text" id="3" class="input"></td>
<td></td>
<td><input type="text" id="5" class="input"></td>
</tr>
<tr>
<td><input type="text" id="6" class="input"></td>
<td><input type="text" id="7" class="input"></td>
<td></td>
<td><input type="text" id="9" class="input"></td>
<td><input type="text" id="10" class="input"></td>
</tr>
<tr>
<td><input type="text" id="11" class="input"></td>
<td><input type="text" id="12" class="input"></td>
<td></td>
<td><input type="text" id="14" class="input"></td>
<td><input type="text" id="15" class="input"></td>
</tr>
</tbody>
</table>
and this is my own demon
I put together a fiddle with the functionality you specified http://jsfiddle.net/tppiotrowski/L7cm8/10/. I hope I understood your requirements correctly. Let me know if you need any alterations or do not understand the code. Good luck!
var active = 0;
//$('#navigate td').each(function(idx){$(this).html(idx);});
rePosition();
$(document).keydown(function(e) {
reCalculate(e);
rePosition();
// if key is an arrow key, don't type the user
// input. if it is any other key (a, b, c, etc)
// edit the text
if (e.keyCode > 36 && e.keyCode < 41) {
return false;
}
});
$('td').click(function() {
active = $(this).closest('table').find('td').index(this);
rePosition();
});
function reCalculate(e) {
var rows = $('#navigate tr').length;
var columns = $('#navigate tr:eq(0) td').length;
var temp;
if (e.keyCode == 37) { //move left or wrap
temp = active;
while (temp > 0) {
temp = temp - 1;
// only advance if there is an input field in the td
if ($('#navigate tr td').eq(temp).find('input').length != 0) {
active = temp;
break;
}
}
}
if (e.keyCode == 38) { // move up
temp = active;
while (temp - columns >= 0) {
temp = temp - columns;
// only advance if there is an input field in the td
if ($('#navigate tr td').eq(temp).find('input').length != 0) {
active = temp;
break;
}
}
}
if (e.keyCode == 39) { // move right or wrap
temp = active;
while (temp < (columns * rows) - 1) {
temp = temp + 1;
// only advance if there is an input field in the td
if ($('#navigate tr td').eq(temp).find('input').length != 0) {
active = temp;
break;
}
}
}
if (e.keyCode == 40) { // move down
temp = active;
while (temp + columns <= (rows * columns) - 1) {
temp = temp + columns;
// only advance if there is an input field in the td
if ($('#navigate tr td').eq(temp).find('input').length != 0) {
active = temp;
break;
}
}
}
}
function rePosition() {
console.log(active);
$('.active').removeClass('active');
$('#navigate tr td').eq(active).addClass('active');
var input = $('#navigate tr td').eq(active).find('input').focus();
scrollInView();
}
function scrollInView() {
var target = $('#navigate tr td:eq(' + active + ')');
if (target.length) {
var top = target.offset().top;
$('html,body').stop().animate({
scrollTop: top - 100
}, 400);
return false;
}
}​
Take a look at this JQFAQ post How to select a table cell using click or navigation keys?
this have some thing you want.

Categories