Calculate Row Total and Grand Total in gridview using jquery - javascript

Hi in below JavaScript code the multiplication is betweentxtQuantity which is textbox TemplateField in grid view and price which is BoundField in grid view.
My issue is my grid view have both txtQuantity and txtPrice as TemplateFieldes
<ItemTemplate><asp:TextBox ID="txtprice" runat="server" Text='<%# Bind("Price") %>'></asp:TextBox></ItemTemplate>
<ItemTemplate><asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox></ItemTemplate>
i have tried to modify the java-script code
$("[id*=lblTotal]", row).html(parseFloat($("[id*=txtprice]", row).html()) * parseFloat($(this).val()));
but it give me NaNas result of multiplication
Original js code
<script type="text/javascript">
$(function () {
$("[id*=txtQuantity]").val("0");
});
$("[id*=txtQuantity]").live("change", function () {
if (isNaN(parseInt($(this).val()))) {
$(this).val('0');
} else {
$(this).val(parseInt($(this).val()).toString());
}
});
$("[id*=txtQuantity]").live("keyup", function () {
if (!jQuery.trim($(this).val()) == '') {
if (!isNaN(parseFloat($(this).val()))) {
var row = $(this).closest("tr");
$("[id*=lblTotal]", row).html(parseFloat($(".price", row).html()) * parseFloat($(this).val()));
}
} else {
$(this).val('');
}
var grandTotal = 0;
$("[id*=lblTotal]").each(function () {
grandTotal = grandTotal + parseFloat($(this).html());
});
$("[id*=lblGrandTotal]").html(grandTotal.toString());
});
</script>

There are some minor issues with your code, try this:
$(function () {
$("[id*=txtQuantity").val("0");
});
$(document).on("change", "[id*=txtQuantity]", function () {
if (isNaN(parseInt($(this).val()))) {
$(this).val('0');
} else {
$(this).val(parseInt($(this).val()).toString());
}
});
$(document).on("keyup mouseup", "[id*=txtQuantity]", function () {
if (!jQuery.trim($(this).val()) == '') {
if (!isNaN(parseFloat($(this).val()))) {
var row = $(this).closest("tr");
$("[id*=lblTotal]", row).html(parseFloat($("[id*=txtPrice]", row).val()) * parseFloat($(this).val()));
}
} else {
$(this).val('');
}
var grandTotal = 0;
$("[id*=lblTotal]").each(function () {
var value = $(this).html();
if(value != "")
grandTotal = grandTotal + parseFloat(value);
});
$("[id*=lblGrandTotal]").html(grandTotal.toString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="5">
<tr>
<td><input type="text" id="txtPrice1" value="100" /></td>
<td><input type="text" id="txtQuantity1" value="1" /></td>
<td><div id="lblTotal1" /></td>
</tr>
<tr>
<td><input type="text" id="txtPrice2" value="200" /></td>
<td><input type="text" id="txtQuantity2" value="2" /></td>
<td><div id="lblTotal1" /></td>
</tr>
<tr>
<td><input type="text" id="txtPrice3" value="300" /></td>
<td><input type="text" id="txtQuantity3" value="3" /></td>
<td><div id="lblTotal1" /></td>
</tr>
</table>
<div id="lblGrandTotal" />

Related

Select multiple check boxes by clicking the first one

I have an html table with many check boxes. If I select the first check box, the next one is automatically selected. Does someone know how to do this? Also, the exact row number in table is unknown.
function toggle(source) {
var row_index = $("#checkFirst").index();
var row_first = $(".row").index();
checkboxes = document.getElementsByName('row');
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (i == row_index && i == row_first) {
checkboxes[i].checked = source.checked;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody data-bind="foreach: list">
<tr>
<td><input type="checkbox" id="checkFirst" onClick="toggle(this)" /></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
</tr>
</tbody>
You can use below code for this. First give class checkbox to all other checkboxes. Hope this can help you
$(function(){
$("#checkFirst").click(function () {
$('.checkbox').attr('checked', this.checked);
});
$(".checkbox").click(function(){
if($(".checkbox").length == $(".checkbox:checked").length) {
$("#checkFirst").attr("checked", "checked");
} else {
$("#checkFirst").removeAttr("checked");
}
});
});
You can try with below code. It will help you.
jQuery file:
https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
<table>
<tbody data-bind="foreach: list">
<tr id="first">
<td><input type="checkbox" id="checkfirst" onClick="toggle('first',this.id)"/></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox" name="row"></td>
</tr>
<tr id="second">
<td><input type="checkbox" id="checksecond" onClick="toggle('second',this.id)"/></td>
<td><input type="checkbox" ></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
</tr>
</table>
Script
<script>
function toggle(source,id) {
chcked = $('#'+id).prop( "checked" );
if(chcked)
{
$('#'+source+' :checkbox').each(function() {
this.checked = true;
});
}
else
{
$('#'+source+' :checkbox').each(function() {
this.checked = false;
});
}
}
</script>
You can try this snippet.
function handleCheck(e) {
let will_change = false;
if (e.shiftKey && this.checked) {
checkboxes.forEach(element => {
if (element === this || element === last_checked) {
will_change = !will_change;
}
if (will_change) {
element.checked = true;
}
});
}
last_checked = this;
}
Then add a click event listener to each of the checkboxes you want to act as a group
https://codepen.io/anon/pen/GyQEJZ
this makes the first checkbox a global control for all
$('#checkFirst').on('change',function(){
if($(this).is(':checked'))
$('input[type="checkbox"]').prop('checked', true);
else
$('input[type="checkbox"]').prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<tbody data-bind="foreach: list">
<tr>
<td><input type="checkbox" id="checkFirst"/></td>
<td><input type="checkbox" name="row"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
<td><input type="checkbox"></td>
</tr>
</tbody>
and this is to select the following checkboxes in the same row
$('input[type="checkbox"]').on('change',function(){
$(this).parent().nextAll().find('input[type="checkbox"]').prop('checked', $(this).is(':checked'));
});

How to find that all input text boxes are empty in table?

I have a html table with data like
<table>
<tr>
<td>abc</td>
<td>781</td>
<td><input id="barcodedb0" class="hide" type="text" /><input id="barcode0" class="hide" type="text" /></td>
</tr>
<tr>
<td>abc</td>
<td>781</td>
<td><input id="barcodedb0" class="hide" type="text" /><input id="barcode0" class="hide" type="text" /></td>
</tr>
</table>
In JQuery
$('#library_info_tbl tbody').on("keyup", "tr td input:nth-child(2)", function() {
if(all the textboxes are empty)
// do something
});
I am trying to find out how will I check that all text boxes in the table are empty.
Note that text boxes with "hide" class are hidden and are used for other purpose.
Please help!!!
You can use this
This code will work only for second input.
$('#library_info_tbl tbody').on("keyup", "tr td input:nth-child(2)", function() {
var oneEmpty = false;
$("#library_info_tbl tbody tr td input:nth-child(2)").filter(function () {
return $.trim($(this).val()) == '';
});
if(oneEmpty)
// do something
});
This code will work only for all input.
$('#library_info_tbl tbody').on("keyup", "tr td input:nth-child(2)", function() {
if($("#library_info_tbl tbody input:empty").length == $("#library_info_tbl tbody input").length)
{
// do something
}
});
// Instead of $("#library_info_tbl tbody input:empty") you can also use $("input.hide:empty")
Try this
var allempty = true;
$('.hide').each(function(){
if($(this).val()!=''){
allempty = false;
}else{
allempty = true;
}
});
if(allempty) {
//this is empty
}
you can use input[type=text] as selector :
For i.e. :
var emptyValues = 0;
$('table input[type=text]').each(function(){
if($(this).val() != ''){
console.log($(this).val());
emptyValues = 1;
}
});
if(emptyValues == 0){
//enter code here
}
Considering the id of your table is tableId, you could try:
if($("table#tableId input[class!='hide'][value='']").length == $("table#tableId input[class!='hide']").length) {
// do something
}
or simply:
if($("table input[class!='hide'][value='']").length == $("table input[class!='hide']").length) {
// do something
}
You can do it by for loop iteration and check each value
function checkEmpty(){
var elems = $("table input[type=text]");
var isEmpty = false;
for(let i=0 ; i < elems.length;i++){
if($(elems[i]).val().trim() != ''){
isEmpty = true;
break;
}
}
$("#isempty").html(isEmpty?'All Not Empty':'All Empty');
//return isEmpty;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>abc</td>
<td>781</td>
<td><input id="barcodedb0" class="hide" type="text" /><input id="barcode0" class="hide" type="text" /></td>
</tr>
<tr>
<td>abc</td>
<td>781</td>
<td><input id="barcodedb1" class="hide" type="text" /><input id="barcode1" class="hide" type="text" /></td>
</tr>
</table>
<input onclick="checkEmpty()" type="button" value="check empty"/>
<div id="isempty"></div>
Care about duplicate id's

How to trigger the event without input enter

I want to calculate the sum of a column consisting multiple row
the values are retrieved from the database and can also be manually alter/
The issue is without the input event, the function are not triggered.
So when the column display multiple rows value, the total amount wont show.
Any idea.Thanks in advance
$(document).ready(function(){
$("#myTable").on('input', '.txtCal', function () {
var calculated_total_sum = 0;
$("#myTable .txtCal").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
});
});
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<table id="myTable">
<tr> <th width="100">Name </th>
<th>Price</th>
</tr>
<tr>
<td><span>A :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
</tr>
<tr>
<td><span>B :</span></td>
<td><input type="text" class='txtCal' value="10"/></td>
</tr>
<tr>
<td><span>C :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
</tr>
<tr>
<td><span><b>TOTAL :</b></span></td>
<td><b><span id="total_sum_value"></span></b></td>
</tr>
</table>
$(document).ready(function(){
$("#myTable").on('input', '.txtCal', function () {
calculate();
});
function calculate() {
var calculated_total_sum = 0;
$("#myTable .txtCal").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
}
calculate();
});
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<table id="myTable">
<tr> <th width="100">Name </th>
<th>Price</th>
</tr>
<tr>
<td><span>A :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
</tr>
<tr>
<td><span>B :</span></td>
<td><input type="text" class='txtCal' value="10"/></td>
</tr>
<tr>
<td><span>C :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
</tr>
<tr>
<td><span><b>TOTAL :</b></span></td>
<td><b><span id="total_sum_value"></span></b></td>
</tr>
</table>
You should move code that calculates price to separate function and call it on 'domready' and 'input' events.
This may helpful
$(document).ready(function(){
var calculated_total_sum;
calSum();
$("#myTable").on('input', '.txtCal', function () {
calSum();
});
function calSum()
{
calculated_total_sum=0;
$("#myTable .txtCal").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
}
});
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<table id="myTable">
<tr> <th width="100">Name </th>
<th>Price</th>
</tr>
<tr>
<td><span>A :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
</tr>
<tr>
<td><span>B :</span></td>
<td><input type="text" class='txtCal' value="10"/></td>
</tr>
<tr>
<td><span>C :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
</tr>
<tr>
<td><span><b>TOTAL :</b></span></td>
<td><b><span id="total_sum_value"></span></b></td>
</tr>
</table>
Just change when the event calculate the value. In your code, you triggered the calculation when the txtCal class are input. You have to create a separate function like this:
function calculate() {
var calculated_total_sum = 0;
$("#myTable .txtCal").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
});
}
$(document).ready(function(){
calculate();
$("#myTable").on('input', '.txtCal', function () {
calculate();
}
});
Hope it helps you
Make a separate function and call it on input and to get the sum when page gets ready with values from database, call it inside document.ready like given below:
function getSum()
{
$("#myTable .txtCal").each(function () {
var calculated_total_sum = 0;
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
});
}
$(document).ready(function(){
getSum();
$("#myTable").on('input', '.txtCal', function () {
getSum();
});
});

How to remeber clicked buttons after page refresh with javascript?

Following code used to highlight table record when the checkbox is clicked. But once I refresh the page highlighted records disappear.How can I remain same highlighted record even after page refresh?
<style>
.highlight {
background-color: yellow;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#Table input").click(function() {
if ($(this).is(":checked")) {
$(this).parent().parent().addClass("highlight");
} else {
$(this).parent().parent().removeClass("highlight");
}
});
});
</script>
<body>
<div class="col-lg-10">
<form name="f">
<table id="Table" border="1"><tr>
<td><input type="checkbox" name="cb1" id="cb1" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" /></td>
<td>Click me</td>
</tr></table>
</div>
You will have to save the state somewhere, either in the url as a query string or you could use the browser localStorage. Then when the page loads, check that state and highlight accordingly.
Try something like this:
$("#Table input").click(function() {
if ($(this).is(":checked")) {
if(!localStorage.checked) {
localStorage.checked = [];
}
localStorage.checked.push($(this));
$(this).parent().parent().addClass("highlight");
} else {
for (var i = 0;i < localStorage.checked.length; i++) {
var itemAtIndex = localStorage.checked[i];
if(itemAtIndex == $(this)){
localStorage.splice(i, 1);
}
}
$(this).parent().parent().removeClass("highlight");
}
});
//on page load
for (var i = 0;i < localStorage.checked.length; i++) {
var itemAtIndex = localStorage.checked[i];
itemAtIndex.parent().parent().addClass("highlight");
}
The idea written in the answer of stackoverfloweth was correct however his code indeed did not work.
Heres your example using localStorage that does work (wont work in preview window here but will if you try it locally):
<style>
.highlight {
background-color: yellow;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
var checked = [];
$(document).ready(function() {
if (localStorage.getItem("checked") == null)
localStorage.setItem("checked", checked);
$("#Table input").click(function() {
if ($(this).is(":checked")) {
$(this).parent().parent().addClass("highlight");
checked.push($(this).attr("id"));
} else {
$(this).parent().parent().removeClass("highlight");
checked.remove($(this).attr("id"));
}
localStorage.setItem("checked", JSON.stringify(checked));
});
var saved = JSON.parse(localStorage.getItem("checked"));
for (var i = 0;i < saved.length; i++) {
var itemAtIndex = $("#" + saved[i] + "");
itemAtIndex.click();
itemAtIndex.parent().parent().addClass("highlight");
}
});
</script>
<body>
<div class="col-lg-10">
<form name="f">
<table id="Table" border="1"><tr>
<td><input type="checkbox" name="cb1" id="cb1" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" /></td>
<td>Click me</td>
</tr></table>
</div>

Show or hide table row if checkbox is checked

I want to hide a table row (with input fields inside) when a checkbox is checked.
I found something that works:
HTML
<table>
<tr id="row">
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="checkbox" id="checkbox">Hide inputs</td>
</tr>
</table>
Script
$(document).ready(function () {
$('#checkbox').change(function () {
if (!this.checked)
$('#row').fadeIn('slow');
else
$('#row').fadeOut('slow');
});
});
Fiddle
But this only works if the checkbox is not checked already. So if the checkbox is checked at the beginning, I want the table row to be hidden. How do I do this?
Please note that I don't know much about JavaScript, but I really need this
trigger .change() event after you attach events:
$(function () {
$('#checkbox1, #checkbox2').change(function () {
var row = $(this).closest('tr').prev();
if (!this.checked)
row.fadeIn('slow');
else
row.fadeOut('slow');
}).change();
});
Note: I make code shorter.
jsfiddle
Just call the change event after you initially register it:
$(document).ready(function () {
$('#checkbox').change(function () {
if (!this.checked)
$('#row').fadeIn('slow');
else
$('#row').fadeOut('slow');
});
$('#checkbox').change();
});
I believe this is what you were looking for:
$(function() {
var init = true;
$('input[type="checkbox"]').change(function() {
if (this.checked) {
if (init) {
$(this).prev().hide();
init = false;
} else $(this).prev().slideUp();
} else $(this).prev().slideDown();
}).change();
});
input[type='text'] {
display: block;
padding: 3px 5px;
margin: 5px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="text" placeholder="Shown" />
<input type="checkbox" />Hide input
</div>
<div>
<input type="text" placeholder="Hidden" />
<input type="checkbox" checked/>Hide input
</div>
Generic solution without hardcoded ids:
$('table :checkbox').change(function(e, speed) {
speed = typeof speed == 'undefined' ? 'slow' : 0;
$(this).closest('tr').prev()[this.checked ? 'fadeOut' : 'fadeIn'](speed);
}).trigger('change', [0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="row1">
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="checkbox" id="checkbox1">Hide inputs</td>
</tr>
<tr id="row2">
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="checkbox" id="checkbox2" checked>Hide inputs</td>
</tr>
</table>
just call the change function in document.ready after it
$('#checkbox').change();
Like this
$(document).ready(function () {
$('#checkbox').change(function () {
if (!this.checked) $('#row').fadeIn('slow');
else $('#row').fadeOut('slow');
});
$('#checkbox').change();
});
Here is the DEMO FIDDLE
Musefan's answer is excelent, but following is also another way!
$(document).ready(function () {
($('#checkbox').prop('checked')==true) ? $('#row').fadeOut('slow'):$('#row').fadeIn('slow');
$('#checkbox').change(function () {
if (!this.checked)
$('#row').fadeIn('slow');
else
$('#row').fadeOut('slow');
});
});
you can initially hide them if you really want the checkbox to be checked initially.
<table>
<tr id="row" style="display: none;">
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="checkbox" id="checkbox" checked>Hide inputs</td>
</tr>
</table>
<script>
$(document).ready(function () {
$('#checkbox').change(function () {
if (!this.checked)
$('#row').fadeIn('slow');
else
$('#row').fadeOut('slow');
});
});
</script>
var showOrHideRow=fucntion(isChecked){
if (isChecked)
$('#row').fadeOut('slow');
else
$('#row').fadeIn('slow');
};
$(document).ready(function () {
showOrHideRow($('#checkbox').is(":checked"));
$('#checkbox').change(function () {
showOrHideRow(this.checked);
});
});
$('#tbl_name tr').find('input:checkbox:checked').closest('tr').show();
$('#tbl_name tr').find('input:checkbox:Unchecked').closest('tr').hide();

Categories

Resources