How to auto calculate the html table using jQuery? - javascript

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!

Related

Clone table rows with select element inside td tag

I'm new to JS. I have a dynamic table (I didn't add the code for add and delete rows) which I want to show in another table. I try to clone every row. Everything is working but td tag with select element doesn't cloned properly. It shows the selected value or the first value if there is no selected. The idea of this clone is to show the table in modal form and the cloned table will be like a preview. Cloning happened when the modal foem is show. In code below I add the button for cloning table. I think, it doesn't matter in this case.
This is the Fiddle link.
Here is my code HTML:
<table class="table table-bordered" id="table" >
<thead>
<tr>
<td >#</td>
<td >Description</td>
<td >Qty</td>
<td >Units</td>
<td >Price without vat</td>
<td >Vat %</td>
<td >Total</td>
<td >Del</td>
</tr>
</thead>
<tr class="product">
<td class="cloned" width="4%" >
<input type="number" class="enumer" style="width:100%; border: none; padding: 0" disabled="disabled">
</td>
<td class="cloned" width="34%">
<input type="text" class="item_product" style="width:100%;" name="product[]">
</td>
<td class="cloned" width="18">
<input style="width:100%;" class="qty" id="qty" name="qty[]" pattern="[+-]?([0-9]+[.,]?[0-9]*)" type="text" value="0" required>
</td>
<td class="cloned" width="7%">
<input id="item_units[]" class="units" style="width:100%;" name="item_units[]" type="text" value="ks">
</td>
<td class="cloned" width="10%">
<input class="price" style="width:100%;" id='price' name="price_unit[]" pattern="[+-]?([0-9]+[.,]?[0-9]*)" value="0" type="text" required>
</td>
<td class="cloned" width="7%" id="vat_td">
<select class="vat" id="vat" name="vat[]" type="text">
<option value="0">0</option>
<option value="10">10</option>
<option value="20">20</option>
</select>
</td>
<input class="hidden" hidden value="1" id="payer_vat_hidden">
<td class="cloned" width="17%">
<input type="number" style="width:100%; background: #dddddd;" class="amount" id="amount" name="amounts[]" readonly>
</td>
<td class="delTD" width="5%">
<button type="button" style="width:100%;" id="deleteRow" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
</table>
<button onclick="copyTable()">copy table</button>
<table class="table table-bordered" id="second_table" >
<thead>
<tr>
<th>#</th>
<th>DESCRIPTION</th>
<th class="text-center">QUANTITY</th>
<th class="text-center">UNITS</th>
<th class="text-right">PRICE</th>
<th class="text-right">Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here is my code Javascript:
function copyTable(){
$("#second_table tr").remove();
$("#table tr").each(function() {
var $target = $("#second_table");
var $tds = $(this).children(),
$row = $("<tr></tr>");
$row.append($tds.eq(0).clone())
.append($tds.eq(1).clone())
.append($tds.eq(2).clone())
.append($tds.eq(3).clone())
.append($tds.eq(4).clone())
.append($tds.eq(5).clone())
.append($tds.eq(6).clone())
.appendTo($target);
});
}

How to add extra row on a table by clicking

I am trying to create an invoice system and I need to add a function to add extra rows.
What I have looks like this:
$(document).ready(function() {
$("#addrow").click(function(){
$(".item-row:last").after('
<tr class="item-row">
<td>#</td>
<td>New Item</td>
<td>New</td>
<td>New</td>
<td>New</td>
<td>New</td>
<td>New</td>
</tr>');
bind();
});
});
<table>
<tr>
<th>#</th>
<th>Type</th>
<th>Location</th>
<th>Item</th>
<th>Cost</th>
<th>Days</th>
<th>Price</th>
</tr>
<tr class="item-row">
<td>1</td>
<td>Type</td>
<td>Location</td>
<td>Item</td>
<td>100</td>
<td>2</td>
<td>200</td>
</tr>
<tr id="hidden-row">
<td colspan=7>
<a id="addrow" href="javascript:;" title="Add a row">Add a row</a>
</td>
</tr>
What I want to do but have no idea how to do it is: click Add a row, and have an extra row to add more products. I did some research and came across some example and I took the code for the script from there but I do not know if I left part of the script out. I am using, html, php and js any help will be greatly appreciated! thank you in advanced.
You need to use `` instead of '' if its multiple line html. Also, you need to use .bind():
$(document).ready(function() {
$("#addrow").click(function() {
$(".item-row:last").after(`
<tr class="item-row">
<td>#</td>
<td>New</td>
<td>New</td>
<td>New</td>
<td>New</td>
<td>New</td>
<td>New</td>
</tr>`)
.bind();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>#</th>
<th>Type</th>
<th>Location</th>
<th>Item</th>
<th>Cost</th>
<th>Days</th>
<th>Price</th>
</tr>
<tr class="item-row">
<td>1</td>
<td>Type</td>
<td>Location</td>
<td>Item</td>
<td>100</td>
<td>2</td>
<td>200</td>
</tr>
<tr id="hidden-row">
<td colspan=7>
<a id="addrow" href="javascript:;" title="Add a row">Add a row</a>
</td>
</tr>
</table>
$(document).ready(function() {
var iCnt=0;
$('#FaqsTable').on('click','#addCF',function() {
if(iCnt<=100) {
iCnt=iCnt+1;
$("#FaqsTable").append('<tr>'+
//'<td> <div class=" col-md-9"><div class="gt_privacy_field default_width"> <input type="text" class="c_ph" id="POID" name="POID[]" value="" placeholder="POID" /></div></div></td>' +
'<td style="display:none"><input type="text" class="c_ph" id="BillDetailID" name="BillDetailID[]" value="0" placeholder="Select Item" style="width:150px" /></td>'+
'<td><input type="text" class="form-control" id="Perticulars" name="Perticulars[]" value="" placeholder="Enter Perticular" style="width:400px"/></td>'+
'<td><input type="text" class="form-control" id="Amount" name="Amount[]" value="0" placeholder="Enter Amount" style="width:150px"/></td>'+
'<td class="hidden" style="display:none"><input type="text" class="Flag sm-form-control" id="Flag" name="Flag[]" value="I" placeholder="Flag" /></td>'+
'<td><p class="fa fa-trash-o m-r-5" style="color:red"></p>Remove</td> '+
'</tr>');
}
});
$("#FaqsTable").on('click','#remCF',function() {
var flag=$(this).closest('tr').find(".Flag").val();
if(flag=="I") {
$(this).closest('tr').remove();
}
else(flag=="U")
{
$(this).closest("tr").hide();
$(this).closest('tr').find(".Flag").val("D");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="form-group row">
<div class="table-responsive">
<table id="FaqsTable" class="table table-bordered nobottommargin">
<tr style="background-color:#b5aeae">
<th style="text-align:center;width:400px;">Perticular </th>
<th style="text-align: center; width: 150px;">Amount </th>
<th style="text-align: center; width: 100px;">Action</th>
<tr />
<tr>
<td style="display:none">
<input type="text" class="form-control" id="BillDetailID" name="BillDetailID[]" value="0" placeholder="ItemName" style="width:150px" required />
</td>
<td>
<input type="text" class="form-control" id="Perticulars" name="Perticulars[]" value="" placeholder="Enter Perticular" style="width:400px" required />
</td>
<td>
<input type="text" class="form-control" id="Amount" name="Amount[]" value="0" placeholder="EnterAmount" style="width:150px" required />
</td>
<td>
<p class="fa fa-plus" style="color:green"></p>Add
</td>
</tr>
</table>
</div>
</div>
$(document).ready(function() {
var iCnt=0;
$('#FaqsTable').on('click','#addCF',function() {
if(iCnt<=100) {
iCnt=iCnt+1;
$("#FaqsTable").append('<tr>'+
//'<td> <div class=" col-md-9"><div class="gt_privacy_field default_width"> <input type="text" class="c_ph" id="POID" name="POID[]" value="" placeholder="POID" /></div></div></td>' +
'<td style="display:none"><input type="text" class="c_ph" id="BillDetailID" name="BillDetailID[]" value="0" placeholder="Select Item" style="width:150px" /></td>'+
'<td><input type="text" class="form-control" id="Perticulars" name="Perticulars[]" value="" placeholder="Enter Perticular" style="width:400px"/></td>'+
'<td><input type="text" class="form-control" id="Amount" name="Amount[]" value="0" placeholder="Enter Amount" style="width:150px"/></td>'+
'<td class="hidden" style="display:none"><input type="text" class="Flag sm-form-control" id="Flag" name="Flag[]" value="I" placeholder="Flag" /></td>'+
'<td><p class="fa fa-trash-o m-r-5" style="color:red"></p>Remove</td> '+
'</tr>');
}
});
$("#FaqsTable").on('click','#remCF',function() {
var flag=$(this).closest('tr').find(".Flag").val();
if(flag=="I") {
$(this).closest('tr').remove();
}
else(flag=="U")
{
$(this).closest("tr").hide();
$(this).closest('tr').find(".Flag").val("D");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="form-group row">
<div class="table-responsive">
<table id="FaqsTable" class="table table-bordered nobottommargin">
<tr style="background-color:#b5aeae">
<th style="text-align:center;width:400px;">Perticular </th>
<th style="text-align: center; width: 150px;">Amount </th>
<th style="text-align: center; width: 100px;">Action</th>
<tr />
<tr>
<td style="display:none">
<input type="text" class="form-control" id="BillDetailID" name="BillDetailID[]" value="0" placeholder="ItemName" style="width:150px" required />
</td>
<td>
<input type="text" class="form-control" id="Perticulars" name="Perticulars[]" value="" placeholder="Enter Perticular" style="width:400px" required />
</td>
<td>
<input type="text" class="form-control" id="Amount" name="Amount[]" value="0" placeholder="EnterAmount" style="width:150px" required />
</td>
<td>
<p style="color:green"></p>Add
</td>
</tr>
</table>
</div>
</div>

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);
});
});
});

Add Row Button adds PHP cell with Select2 option

Sorry about the Q form but I couldn't find a better way to explain it.
I have a view table that have drop down form that retrieves its options from the DB to be inserted, and it have an add button to add new row to insert.
But the drop down works on Select2 forms, and it's included in the table, so every time I try to add new row it gives it the same id as the previous one and that conflicts with the JS for the Select2 as it needs to get special id for every drop down I made with it.
here's the table and the add button code
<div class="row">
<div class="table-responsive">
<table class="table table-bordered" id="tab_logic">
<thead>
<tr>
<th>Brand Name</th>
<th>Item Name</th>
<th>Model Number</th>
<th class="col-md-2">Item Description</th>
<th>Part Number</th>
<th>Unit</th>
<th class="col-md-1">QTY</th>
<th class="col-md-1">Unit Price (SR)</th>
<th class="col-md-1">Total Price (SR)</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<div class="form-group">
<?php
$query = $con->query("SELECT products_itemDescription FROM pruc_products"); // Run your query --> For Item Desc.
echo '<select class="form-control" id="DescriptionS2forms" name="itemDescription">'; // Open your drop down box
echo '<option value="" selected="selected" disabled></option>'; //Empty Value for VALIDATION
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['products_itemDescription'].'">'.$row['products_itemDescription'].'</option>';
}
echo '</select>';// Close your drop down box
?>
</div>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<strong>Record</strong>
</td>
<td>
<div>
<input class="form-control" type="number" name="requestQTY" required>
</div>
</td>
<td>
<div>
<input class="form-control" type="number" name="requestUnit" step="0.01" min="0.01" max="1000000" required>
</div>
</td>
<td>
<strong>Record</strong>
</td>
<td class="col-md-1" id="deleteBtn">
<a class="btn btn-default deleteBtn">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- End of 3rd Row -->
<div class="row">
<a id="add_row" class="btn btn-default pull-right">Add</a>
</div>
And the JS for the add button and select2 function:
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
var x = '[{<td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><div class="form-group"> <?php $query = $con->query('SELECT products_itemDescription FROM pruc_products'); echo '<select class="form-control" id=DescriptionS2forms'.(i+1).'" name="itemDescription">'; echo '<option value="" selected="selected" disabled></option>'; while($row = $query->fetch(PDO::FETCH_ASSOC)) {echo '<option value="'.$row['products_itemDescription'].'">'.$row['products_itemDescription'].'</option>';} echo '</select>'; ?> </div></td> <td><strong>Record</strong></td> <td><strong>Record</strong></td> <td><div><input class="form-control" type="number" name="requestQTY" required></div></td> <td><div><input class="form-control" type="number" name="requestUnit" step="0.01" min="0.01" max="1000000" required></div></td> <td><strong>Record</strong></td> <td class="col-md-1" id="deleteBtn"> <a class="btn btn-default deleteBtn">Delete</a></td>}]';
$('#tab_logic').append('<tr id="addr' + (i + 1) + '">' + x + '</tr>');
i++;
});
$("#SupplierS2forms, #ProjectS2forms, #WHS2forms, #DescriptionS2forms").select2(); });
in the PHP option it gives the id="DescriptionS2forms"
so I need to add a number for the id so I can use it in the Select2 Function as it doesn't accept same id
Example
id="DescriptionS2forms1" AND id="DescriptionS2forms2"

how to write javascript calculated array

Why the 2 array can't press + or -
So i wanna get this price & quantity will sum and get value in amount
when you also and price and the system will be get the value out in amount the total in below will be change ( it extract from amount )
<table class="table table-striped table-hover">
<thead>
<tr>
<th class="span1" style="text-align:center;">Delete</th>
<th class="span12" style="text-align:center;">Name</th>
<th class="span2" style="text-align:center;">Price</th>
<th class="span2" style="text-align:center;">Quantity</th>
<th class="span2" style="text-align:center;">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center; vertical-align:middle;">
<a class="btn-danger" href=""><i class="icon-remove icon-white"></i></a>
</td>
<td style="text-align:left; vertical-align:middle;">test</td>
<td style="text-align:center; vertical-align:middle;">24</td>
<td style="text-align:center; vertical-align:middle;">
<div class="input-append">
<input class="input-mini" type="text" id="quantity[]" name='prd_num[]' value='1' style="text-align:center;">
<button class="btn" type="button" id="up"><i class="icon-plus"></i></button>
<button class="btn" type="button" id="down"><i class="icon-minus"></i></button>
</div>
</td>+63
<td style="text-align:right; vertical-align:middle;"></td>
</tr>
<tr>
<td style="text-align:center; vertical-align:middle;">
<a class="btn-danger" href=""><i class="icon-remove icon-white"></i></a>
</td>
<td style="text-align:left; vertical-align:middle;">test</td>
<td style="text-align:center; vertical-align:middle;">24</td>
<td style="text-align:center; vertical-align:middle;">
<div class="input-append">
<input class="input-mini" type="text" id="quantity[]" name='prd_num[]' value='1' style="text-align:center;">
<button class="btn" type="button" id="up"><i class="icon-plus"></i></button>
<button class="btn" type="button" id="down"><i class="icon-minus"></i></button>
</div>
</td>+63
<td style="text-align:right; vertical-align:middle;"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3"></td>
<td style="text-align:center; vertical-align:middle;">
<strong>Total</strong>
</td>
<td style="text-align:right; vertical-align:middle;"></td>
</tr>
</tfoot>
</table>
The JavaScript is as follows:
button_up=document.getElementById('up');
button_down=document.getElementById('down');
button_up.onclick=function() {setQuantity('up');}
button_down.onclick=function() {setQuantity('down');}
quantity = document.getElementById('quantity[]');
function setQuantity(upordown) {
if (quantity.value > 1) {
if (upordown == 'up') {++quantity.value;}
else if (upordown == 'down') {--quantity.value;}
}
else if (quantity.value == 1) {
if (upordown == 'up') {++quantity.value;}
}
else
{quantity.value=1;}
}
http://jsfiddle.net/Danglebz/ucdpx/
a lot of small fixes
same id for different objects are not good
and the js code have to be more portable, so if you have 1000 lines it'll work
the best way would be to use event delegation but there's a version
function setQuantity(e) {
var upordown = $(e.target).hasClass("up") ? "up" : "down"
, objQt = $(e.target).closest("div").find("input");
if (parseInt(objQt.val(), 10) > 1) {
if (upordown == 'up'){objQt.val(parseInt(objQt.val(),10)+1);}
else if (upordown == 'down'){objQt.val(parseInt(objQt.val(),10)-1);}}
else if (objQt.val() == 1) {
if (upordown == 'up'){objQt.val(parseInt(objQt.val(),10)+1);}}
else
{objQt.val(1);}
}
$(".btn").click(setQuantity);
http://jsfiddle.net/ucdpx/2/

Categories

Resources