How to compute total price based on checkboxes - javascript

In our website I have a cart table that contains all of the items. Each row has checkboxes. By clicking the checkboxes, it will determine the total price of your cart the you will checkout. At first I don't know what the title of my question should be as I have 2 problems.
First, when I clicked all the checkboxes, the Select all checkbox will be checked, and if I unchecked one, the Select all will be unchecked.
Second, is properly getting the total prices based on checkboxes. I am able to get the total price when I tick the checkboxes. It all adds up but if I tick the Select all while all other checkboxes are checked, it adds another total which is not right. Please see the demo I uploaded. Total Price Computation Demo
I'm guessing its because I have put computation in Select all also, but I actually run out of ideas on how to achieve this.
Here are my codes
Table
<table class="table">
<thead>
<tr>
<th><input type="checkbox" name="" id="" class="select_all"></th>
<th scope="col">Preview</th>
<th scope="col">Product</th>
<th class="text-right" scope="col">Price</th>
<th scope="col">Quantity</th>
<th class="text-right" scope="col">Total</th>
<th scope="col"></th>
</tr>
</thead>
<tbody class="product-container">
<?php
$cart_items = $cakeOrdering->get_data("SELECT * FROM vw_cart_items ORDER BY cart_itemID DESC");
if(!empty($cart_items)){
if(is_array($cart_items) || is_object($cart_items)){
foreach($cart_items as $cart_item){
?>
<tr data-id="<?php echo $cart_item['cart_itemID'];?>">
<td><input type="checkbox" name="cart_checkbox" class="cart_checkbox"></td>
<td>
<img src="../img/cake_uploads/<?php echo $cart_item['image']; ?>" alt="<?php $cart_item['prod_name']; ?>" class="cart_preview">
</td>
<td><?php echo $cart_item['prod_name']; ?></td>
<td class="price text-right" data-price="<?php echo $cart_item['price']; ?>">₱ <?php echo number_format($cart_item['price'], 2, ".", ","); ?></td>
<td>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary minus_qty" type="button">-</button>
</div>
<input type="number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="text-center quantity" aria-label="quantity" aria-describedby="quantity" value="<?php echo $cart_item['qty']; ?>" disabled>
<div class="input-group-append">
<button class="btn btn-outline-secondary add_qty" type="button">+</button>
</div>
</div>
</td>
<td class="total_price text-right" data-total_price="<?php echo $cart_item['total_price']; ?>">₱ <?php echo number_format($cart_item['total_price'], 2, ".", ",");?></td>
<td class="btn-action">
<i class="fa fa-pencil"></i>
<i class="fa fa-trash"></i>
</td>
</tr>
<?php }}} ?>
</tbody>
</table>
Script
var overall_total = 0;
$('.select_all').on('change', function(){
$('.cart_checkbox').not(this).prop('checked', this.checked);
if($(this).is(":checked")) {
$('.total_price').each(function(){
total_price = $(this).data('total_price');
overall_total = overall_total + parseFloat(total_price);
});
}else{
$('.total_price').each(function(){
total_price = $(this).data('total_price');
overall_total = overall_total - parseFloat(total_price);
});
}
$('.overall_total').text(formatToCurrency(overall_total));
});
$(".cart_checkbox").change(function(){
var total_price = $(this).closest('tr').find('.total_price').data('total_price');
if($(this).is(":checked")) {
overall_total = overall_total + parseFloat(total_price);
}else{
overall_total = overall_total - parseFloat(total_price);
}
$('.overall_total').text(formatToCurrency(overall_total));
})

For your first issue you can check if the length of total checkboxes and checked checkboxes are not equal depending this check/uncheck your select_all checkbox .
Now, for next issue i have move whole calculation part inside different function so whenever you need to total you can call this function and then loop through only checked trs row and change total values .
Demo Code :
$('.select_all').on('change', function() {
$('.cart_checkbox').not(this).prop('checked', this.checked);
sum(); //call this
});
$(".cart_checkbox").change(function() {
var total_length = $(".cart_checkbox").length;
var checked_length = $(".cart_checkbox:checked").length
//check if length less then total
if (checked_length < total_length) {
$('.select_all').prop('checked', false); //uncheck..
} else {
$('.select_all').prop('checked', true); //check
}
sum(); //call this
})
function sum() {
var overall_total = 0;
//loop through only checked trs..
$(".cart_checkbox:checked").closest("tr").find('.total_price').each(function() {
total_price = $(this).data('total_price');
overall_total = overall_total + parseFloat(total_price);
})
$('.overall_total').text(overall_total); //add your format fn
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th><input type="checkbox" name="" id="" class="select_all"></th>
<th scope="col">Preview</th>
<th scope="col">Product</th>
<th class="text-right" scope="col">Price</th>
<th scope="col">Quantity</th>
<th class="text-right" scope="col">Total</th>
<th scope="col"></th>
</tr>
</thead>
<tbody class="product-container">
<tr data-id="1">
<td><input type="checkbox" name="cart_checkbox" class="cart_checkbox"></td>
<td>
<img src="../img/cake_uploads/<?php echo $cart_item['image']; ?>" alt="<?php $cart_item['prod_name']; ?>" class="cart_preview">
</td>
<td>A</td>
<td class="price text-right" data-price="34">₱ 34</td>
<td>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary minus_qty" type="button">-</button>
</div>
<input type="number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="text-center quantity" aria-label="quantity" aria-describedby="quantity" value="<?php echo $cart_item['qty']; ?>" disabled>
<div class="input-group-append">
<button class="btn btn-outline-secondary add_qty" type="button">+</button>
</div>
</div>
</td>
<td class="total_price text-right" data-total_price="74">₱ 74</td>
<td class="btn-action">
<i class="fa fa-pencil"></i>
<i class="fa fa-trash"></i>
</td>
</tr>
<tr data-id="2">
<td><input type="checkbox" name="cart_checkbox" class="cart_checkbox"></td>
<td>
<img src="../img/cake_uploads/<?php echo $cart_item['image']; ?>" alt="<?php $cart_item['prod_name']; ?>" class="cart_preview">
</td>
<td>A2</td>
<td class="price text-right" data-price="34">₱ 34</td>
<td>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary minus_qty" type="button">-</button>
</div>
<input type="number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="text-center quantity" aria-label="quantity" aria-describedby="quantity" value="<?php echo $cart_item['qty']; ?>" disabled>
<div class="input-group-append">
<button class="btn btn-outline-secondary add_qty" type="button">+</button>
</div>
</div>
</td>
<td class="total_price text-right" data-total_price="742">₱ 742</td>
<td class="btn-action">
<i class="fa fa-pencil"></i>
<i class="fa fa-trash"></i>
</td>
</tr>
<tr data-id="3">
<td><input type="checkbox" name="cart_checkbox" class="cart_checkbox"></td>
<td>
<img src="../img/cake_uploads/<?php echo $cart_item['image']; ?>" alt="<?php $cart_item['prod_name']; ?>" class="cart_preview">
</td>
<td>A3</td>
<td class="price text-right" data-price="343">₱ 343</td>
<td>
<div class="input-group input-group-sm mb-3">
<div class="input-group-prepend">
<button class="btn btn-outline-secondary minus_qty" type="button">-</button>
</div>
<input type="number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' class="text-center quantity" aria-label="quantity" aria-describedby="quantity" value="<?php echo $cart_item['qty']; ?>" disabled>
<div class="input-group-append">
<button class="btn btn-outline-secondary add_qty" type="button">+</button>
</div>
</div>
</td>
<td class="total_price text-right" data-total_price="743">₱ 743</td>
<td class="btn-action">
<i class="fa fa-pencil"></i>
<i class="fa fa-trash"></i>
</td>
</tr>
</tbody>
</table>
<span class="overall_total"></span>

Just make overall_total = 0 inside your $('.select_all').on('change' and it should work. And remove else portion.
$('.select_all').on('change', function(){
$('.cart_checkbox').not(this).prop('checked', this.checked);
// reset total value to 0 because in below every product values are being fetched and summed up.
overall_total = 0;
if($(this).is(":checked")) {
$('.total_price').each(function(){
total_price = $(this).data('total_price');
overall_total = overall_total + parseFloat(total_price);
});
}
//else{
// $('.total_price').each(function(){
// total_price = $(this).data('total_price');
// overall_total = overall_total - parseFloat(total_price);
// });
//}
$('.overall_total').text(formatToCurrency(overall_total));
});

Related

How to auto calculate the html table using jQuery?

Can someone or anybody help me on how to auto calculate total price in the table? Please see the image below:
Here's my code (I will included only the code that I used in the Image):
HTML:
<div class="col-12">
<div class="col drop">
<table name="services">
<tr name="services">
<td>
<select class="form-control serv" name="txt-service" id="txt-service"> //dynamic services (from database)
<option value="" readonly>--- Select Service ---</option>
<?php include "include/connect.php";
$sql="SELECT service_id,services,price FROM tbl_serviceoffered";
foreach ($con->query($sql) as $row){
echo "<option value=$row[service_id] data-price=$row[price] data-service=$row[services]>$row[services]</option>";
}
echo "</select>";
?>
</td>
<td><input type="hidden" style="text-align:right" class="form-control" name="service" id="showservice" readonly></td>
<td><input type="text" style="text-align:right" class="form-control" name="price" id="showprice" readonly></td>
<td><input type="text" style="text-align:right" class="form-control" name="item_total" id="item_total"></td>
<td><button class="btn btn-primary" name="add">Add</button></td>
</tr>
</table>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover table-bordered table-striped" name="transactions" id="transactions">
<thead>
<th></th>
<th style="text-align:center">Service Name</th>
<th style="text-align:center">Service Price</th>
<th style="text-align:center">Service Total</th>
</thead>
<tbody>
</tbody>
</table>
<td colspan="2" class="tr"> </td>
<div class="text-right">
<tr>
<td><b>Total</b></td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" style="text-align:right; font-weight:bold" class="form-control" name="grand_total" id="grand_total" placeholder="Total"></td>
</tr>
<tr>
<td>Cash Tendered</td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" type="text" name="cashtendered" placeholder="Cash Tendered"></td>
</tr>
<tr>
<td>Change</td>
<td colspan="2" style="text-align: right"><input class="form-control input-sm" style="width:300px;margin-left:auto" type="text" name="change" placeholder="Change"></td>
</div>
</div>
</div>
<div class="text-right">
<button type="button" class="btn btn-primary btn-icon icon-right" name="btnSaveTransaction" id="btnSaveTransaction"><i class="fas fa-file-invoice"></i> Process Payment</a>
</div>
JS:
var id = 1;
/*Assigning id and class for tr and td tags for separation.*/
$("button[name=add]").click(function() {
var newid = id++;
$("table[name=transactions]").append('<tr id="'+newid+'">\n\
<td style="text-align:center;"><a class="btn btn-primary" href="javascript:void(0);" id="remove">Remove</a></td>\n\
<td width="100px" style="display:none;">' +newid+ '</td>\n\
<td style="text-align:center; display:none;" class="num'+newid+'">' + $("#txt-transact_num").val() + '</td>\n\
<td style="text-align:center; display:none;" class="date'+newid+'">' + $("#txt-transact_date").val() + '</td>\n\
<td style="text-align:center; display:none;" class="patientid'+newid+'">' + $("#txt-patient_id").val() + '</td>\n\
<td style="text-align:center;" class="serv'+newid+'">' + $("#showservice").val() + '</td>\n\
<td style="text-align:center; display:none;" class="servid'+newid+'">' + $(".serv option:selected").val() + '</td>\n\
<td style="text-align:right;" class="price'+newid+'">₱' + $("#showprice").val() + '</td>\n\
<td style="text-align:right;" name="txt" class="totalprice'+newid+'">₱' + $("#item_total").val() + '</td>');
$("#txt-service").val("");
$("#showprice").val("");
$("#item_total").val("0.00");
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("tbody").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#grand_total").val(sum.toFixed(2));
}
$("#transactions").on('click', '#remove', function() {
$(this).parent().parent().remove();
calculateSum();
});
As you can see, in the image above, when I add or pick some services that shows the total each of them, the textbox "total" fetch 0.00 only.
I'm still beginner in this programming language. I hope everyone can help me for our Capstone Project. Thank you!

When increase in quantity results increase in price

In a table I have products and their quantity and price. I'm using plus and minus buttons to increase or decrease the quantity of the product. I also want to increase and decrease the price according to the quantity. Can anyone help me?
<table>
<thead>
<tr>
<th scope="col">Company</th>
<th scope="col">Product</th>
<th width="200px">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td id="Company"></td>
<td id="Product"></td>
<td>
<div class="input-group">
<span class="input-group-btn"><button class="btn btn-default value-control" data-
action="minus" data-target="font-size"><span class="glyphicon glyphicon-minus">
</span></button>
</span>
<input type="text" value="1" class="form-control" id="font-size">
<span class="input-group-btn"><button class="btn btn-default value-control" data-action="plus" data-target="font-size"><span class="glyphicon glyphicon-plus"></span></button>
</span>
</div>
</td>
<td id="Price"></td>
</tr>
</tbody>
</table>
$('#productSelect').change(function() {
var id = $(this).val();
if (id > 0) {
$.get("GetProduct", {
productId: id
}, function(result) {
console.log(result)
$("#Company").text(result.CompanyName);
$("#Product").text(result.ProductName);
$("#Quantity").text(result.ProductQuantity);
$("#Price").text(result.ProductPrice);
});
}
})
$(document).on('click', '.value-control', function() {
var action = $(this).attr('data-action')
var target = $(this).attr('data-target')
var value = parseFloat($('[id="' + target + '"]').val());
if (action == "plus") {
value++;
}
if (action == "minus") {
value--;
}
$('[id="' + target + '"]').val(value)
})
here is my code
$(document).ready(function(){
var priceProduct = $("#priceProduct").attr('data-price');
var total = $("#priceProduct").attr('data-total');
var qty=1;
$(".quantity").click(function(){
if($(this).attr('data-action') == 'minus'){
if(qty == 1){
qty =1;
return false;
}else{
qty =qty-1;
total = parseInt(total) - parseInt(priceProduct);
}
}else{
qty =qty+1;
total = parseInt(priceProduct) + parseInt(total);
}
$("#quantity_input").val(qty);
$("#priceProduct").attr('data-total',total)
$("#Price").text("$"+total);
});
$("#Price").text("$"+total);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<table>
<span id="priceProduct" data-price='10' data-total='10'>let suppose price would be $10</span>
<thead>
<tr>
<th scope="col">Company</th>
<th scope="col">Product</th>
<th width="200px">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td id="Company"></td>
<td id="Product"></td>
<td>
<div class="input-group ">
<span class="input-group-btn">
<button class="btn btn-default value-control quantity"
data-action="minus" data-target="font-size"><span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="text" value="1" class="form-control" id="quantity_input">
<span class="input-group-btn">
<button class="btn btn-default value-control quantity" data-action="plus" data-target="font-size">
<span class="glyphicon glyphicon-plus " ></span>
</button>
</span>
</div>
</td>
<td id="Price"></td>
</tr>
</tbody>
</table>

How to get a multiple of two text box that is generate by dynamic input box

I want to multiply 2 input box (man_day_rates * estimated_man_days) but the input is dynamically generate and display it in subtotal.The problem is I only can calculate the first input, when i press add button, the second input does cannot calculate.
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row1'+i+'"><td style="border:none;"></td>\
<td style="border:none;">\
<input id="man_day_rates'+i+'" class="form-control col-md-7 col-xs-12" type="number" min="1" name="man_days_rate[]" >\
</td>\
<td style="border:none;">\
<input id="estimated_man_days'+i+'" class="form-control col-md-7 col-xs-12" type="number" min="1" name="estimated_man_days[]">\
</td>\
<td style="border:none;"> <input id="result2" type="text" name="" value=""/></td>\
<td style="height: 20px;line-height: 20px;white-space: nowrap; border:none;"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-xs btn_remove">X</button></td>\
</tr> ');
});
$(document).ready(function(){
var man_day_rates = $('#man_day_rates1');
var estimated_man_days = $('#estimated_man_days1');
estimated_man_days.keyup(function(){
var total=isNaN(parseInt(estimated_man_days.val()* man_day_rates.val())) ? 0 :(man_day_rates.val()* estimated_man_days.val());
//$("#result").val(total);
alert(total);
});
man_day_rates.keyup(function(){
var total=isNaN(parseInt(estimated_man_days.val()* man_day_rates.val())) ? 0 :(man_day_rates.val()* estimated_man_days.val());
//$("#result").val(total);
alert(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="table-responsive">
<table class="table table-striped" id="dynamic_field" style="padding:0px;">
<thead>
<tr class="headings">
<th class="column-title">#</th>
<th class="column-title">Item Title</th>
<th class="column-title">Description </th>
<th class="column-title" style="width:100px;">Man Day Rates (RM)</th>
<th class="column-title" style="width:100px;">Estimated Man Days </th>
<th class="column-title"style="width:100px;">Subtotal (RM)</th>
<th class="column-title"style="width:100px;"></th>
</th>
</tr>
</thead>
<tbody>
<tr id="row01">
<?php
$i = 1;
?>
<td style="border:none;">
<input id="man_day_rates<?php echo $i; ?>" class="form-control col-md-7 col-xs-12" type="number" min="1" name="man_days_rate[]" >
</td>
<td style="border:none;">
<input id="estimated_man_days<?php echo $i; ?>" class="form-control col-md-7 col-xs-12" type="number" min="1" name="estimated_man_days[]">
</td>
<td id=""> <input id="result" type="text" name="" value=""/></td>
<td class="add_remove_button" style="height: 20px;line-height: 20px;white-space: nowrap;"></td>
</tr>
</tbody>
</table>
</div>
<div><button id="add" type="button" class="btn btn-primary "><span class="fa fa-plus" style="margin-right:5px;"></span>Add Items</button></div>
I want to multiply 2 input box (man_day_rates * estimated_man_days) but the input is dynamically generate and display it in subtotal.The problem is I only can calculate the first input, when i press add button, the second input does cannot calculate.
you have to initialize your key event each time when you add new control dynamically.
Try like below.
$(document).ready(function(){
$('#add').click(function(){
i++;
//Add field document History
$('#dynamic_field').append('<tr id="row1'+i+'"><td style="border:none;"></td>\
<td style="border:none;">\
<input id="man_day_rates'+i+'" class="form-control col-md-7 col-xs-12" type="number" min="1" name="man_days_rate[]" >\
</td>\
<td style="border:none;">\
<input id="estimated_man_days'+i+'" class="form-control col-md-7 col-xs-12" type="number" min="1" name="estimated_man_days[]">\
</td>\
<td style="border:none;"> <input id="result2" type="text" name="" value=""/></td>\
<td style="height: 20px;line-height: 20px;white-space: nowrap; border:none;"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-xs btn_remove">X</button></td>\
</tr> ');
var man_day_rates = $('#man_day_rates'+i);
var estimated_man_days = $('#estimated_man_days'+i);
estimated_man_days.keyup(function(){
var total=isNaN(parseInt(estimated_man_days.val()* man_day_rates.val())) ? 0 :(man_day_rates.val()* estimated_man_days.val());
//$("#result").val(total);
alert(total);
});
man_day_rates.keyup(function(){
var total=isNaN(parseInt(estimated_man_days.val()* man_day_rates.val())) ? 0 :(man_day_rates.val()* estimated_man_days.val());
//$("#result").val(total);
alert(total);
});
});
});

Jquery moving to next row's input element by id

$('#Cart tbody tr #quantity').on('keydown', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
$(this).closest('tr').next().find('input[type=number]').focus();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="Cart" style="border-color: transparent;" class="table table-hover table-striped well">
<thead class="thead-inverse">
<tr>
<th class="col-lg-1 text-center">Quanity</th>
<th class="col-lg-3 text-center">Comment</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
<tbody>
<tr id="7392036">
<td class="col-lg-1 text-center">
<input type="number" class="form-control" id="quantity" value="0">
</td>
<td class="text-center col-lg-3">
<input type="text" maxlength="15" class="form-control" id="inputforcomment" value="">
</td>
<td class="col-lg-1 text-center">
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
<tr id="7392036">
<td class="col-lg-1 text-center">
<input type="number" class="form-control" id="quantity" value="0">
</td>
<td class="text-center col-lg-3">
<input type="text" maxlength="15" class="form-control" id="inputforcomment" value="">
</td>
<td class="col-lg-1 text-center">
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
<tr id="7392036">
<td class="col-lg-1 text-center">
<input type="number" class="form-control" id="quantity" value="0">
</td>
<td class="text-center col-lg-3">
<input type="text" maxlength="15" class="form-control" id="inputforcomment" value="">
</td>
<td class="col-lg-1 text-center">
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
<tr id="7392036">
<td class="col-lg-1 text-center">
<input type="number" class="form-control" id="quantity" value="0">
</td>
<td class="text-center col-lg-3">
<input type="text" maxlength="15" class="form-control" id="inputforcomment" value="">
</td>
<td class="col-lg-1 text-center">
<button type="button" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
</tbody>
</table>
I have a table with multiple rows and each row has two inputs. Both have different ids. I'm trying to focus on next row's input element by selecting the id when user presses tab key . Here's my code:
$('#Cart tbody tr #quantity').on('keydown', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
$(this).closest('tr').next().find('#quantity').focus();
}
});
While doing this, it selects the wrong textbox on the next row.Any help would be appreciated. thanks
No jQuery required. Just use the tabindex attribute and hook into the browser's native behaviour for applying focus state on tab key presses.
Example:
<table>
<tr>
<td>
<input type="text" tabindex="1">
</td>
</tr>
<tr>
<td>
<input type="text" tabindex="2">
</td>
</tr>
</table>
Recommended for accessibility too.

how to add a checkbox in a datatable php

I have a table that displays the result of a query. I am using codeigniter by the way. I want to add a checkbox in every row. And everytime a checkbox is checked, I will enable the edit button and the delete button..
I made it this way but only on the first row, it enable and disable the button:
<div style="margin-top: 10px;margin-left: 10px;margin-bottom: 10px">
<a type="button" class="btn btn-default" href="<?php echo site_url('home/create')?>" ><span class=" fa fa-plus-circle"></span> Create </a>
<button type="button" id="edit" class="btn btn-default" disabled><span class=" fa fa-edit "></span> Edit</button>
<button type="button" class="btn btn-default" disabled > <span class=" fa fa-trash-o"></span> Delete</button>
</div>
<div class="table-responsive" style="margin-right: 10px;margin-left: 10px;margin-bottom: 10px">
<table class="table table-bordered table-hover table-striped" id="recorddata">
<thead class="header">
<tr class="well">
<th style="width: 1px"></th>
<th style="font-size: 14px;" >Date</th>
<th style="font-size: 14px;">Name</th>
<th style="font-size: 14px;">Status</th>
</tr>
</thead>
<tbody >
<?php if($result!=null){
foreach($result as $row){?>
<tr>
<td align="center"><input type="checkbox" id="recs" name="recs[]" value="<?php echo $row->id;?>"/></td>
<td style="font-size: 15px;padding-left: 20px;"><?php echo $row->datee;?></td>
<td style="font-size: 15px;padding-left: 20px;"><?php echo $row->name;?></td>
<td style="font-size: 15px;padding-left: 20px;"><?php echo $row->status;?></td>
</tr>
<?php }
}
?>
</tbody>
</table><!-- END Table--></div>
here's my jquery:
<script>
$('#recs').click(function() {
if($('#recs').is(":checked")){
$('#edit').prop('disabled',false)
}
else{
$('#edit').prop('disabled',true)
}
});
</script>
You have to class instead of using id for the checkbox. Check if any of the checkbox is checked and enable edit, delete button.
<td align="center"><input type="checkbox" class="recs" name="recs[]" value="<?php echo $row->id;?>"/></td>
Add class in this line
<td align="center"><input type="checkbox" id="recs" name="recs[]" value="<?php echo $row->id;?>"/></td>
Bind jquery on change event like
$(document).ready(function(){
$('.your_class').click(function(){
// check if checkbox is checked
var checked = false;
$(".your_class").each(function () {
if($(this).is(":checked"))
{
checked = true;
}
});
if(checked)
{
// enable buttons here
return;
}
// disable buttons here
});
});

Categories

Resources