When increase in quantity results increase in price - javascript

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>

Related

How to compute total price based on checkboxes

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

How to get html-table tbody inputs value that are dumped by lodash _.template?

This is a Basic Html table to dump tbody by using lodash _.template.
Html Table is:
<div id="attribute-values-wrapper">
<div class="table-responsive">
<table class="options table table-bordered">
<thead>
<tr>
<th></th>
<th>Value</th>
<th></th>
</tr>
</thead>
<tbody id="attribute-values">
</tbody>
</table>
</div>
</div>
Lodash _.template is:
<script type="text/html" id="attribute-value-template">
<tr>
<td class="text-center">
<span class="drag-icon">
<i class="fa"></i>
<i class="fa"></i>
</span>
</td>
<td>
<input type="hidden" name="values[<%- valueId %>][id]"
value="<%- value.id %>">
<div class="form-group">
<input type="text" name="values[<%- valueId %>][value]"
value="<%- value.value %>" class="form-control">
</div>
</td>
<td class="text-center">
<button type="button" class="btn btn-default delete-row"
data-toggle="tooltip" data-title="Delete Value">
<i class="fa fa-trash"></i>
</button>
</td>
</tr>
</script>
Simple javascript function to dump tbody.
let valuesCount = 0;
function addAttributeValue(value = {id: '', value: ''}) {
let template = _.template($('#attribute-value-template').html());
let html = template({valueId: valuesCount++, value});
$('#attribute-values').append(html);
}
The solution to my question.
let attribute_values = [];
$('#attribute-values tr').each(function (index, element) {
let inputs = $(this).find('input'), o = {};
inputs.each(function () {
let name = $(this).attr('name');
if (name === "values[" + index + "][id]") {
o["id"] = this.value;
} else if (name === "values[" + index + "][value]") {
o["value"] = this.value;
}
});
attribute_values.push(o);
});

Webform Validation in MVC

I want to add some validation to my web form, the user inputs are created in a dynamic table**(user can add and delete rows)**, basically the user will click submit when they have completed, and i will call a java script function to build me a list to pass to my controller, my question is how i can validate the users inputs to ensure its right data type etc before the list is built
HTML
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="tab-content" id="tab_logic" name="table1">
<thead>
<tr>
<th class="text-center" style="width: 25px">
#
</th>
<th class="text-center" style="width: 150px">
Status
</th>
<th class="text-center" style="width: 250px">
Actions
</th>
<th class="text-center" style="width: 150px">
Target
</th>
<th class="text-center" style="width: 100px">
Progress
</th>
<th class="text-center" style="width: 250px">
Comments
</th>
</tr>
</thead>
<tbody id="mainData">
<tr id='entry1'>
<td>
1
</td>
<td>
<div class="form-group">
<select name="select" class="form-control" id="status1">
<option disabled="disabled" selected="selected">Select:</option>
<option style="color: green; background-color: white">Competent</option>
<option style="color: orange; background-color: white">Improvement-Required</option>
<option style="color: red; background-color: white">Below Average</option>
</select>
</div>
</td>
<td>
<textarea class="form-control" id='action1'></textarea>
</td>
<td>
<input type="date" class="form-control" id='target1'/>
</td>
<td>
<input type="text" class="form-control" id='progress1' required="required"/>
</td>
<td>
<textarea class="form-control" id='comments1'></textarea>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<a id="add_row" class="btn btn-primary btn-sm pull-left">Add Row</a>
<a id='delete_row' class="btn btn-primary btn-sm">Delete Row </a>
<input type="button" value="Submit" id="subButton" widthvalue="Submit" class="btn btn-primary btn-sm" style="vertical-align: bottom"/>
</div>
</div>
Javascript
$("#subButton")
.click(function() {
for (var j = 1; j <= x; j++) {
var statusEntered = document.getElementById("status" + j).value;
var actionsEntered = document.getElementById("action" + j).value;
var targetEntered = document.getElementById("target" + j).value;
var progessEntered = document.getElementById("progress" + j).value;
var commentsEntered = document.getElementById("comments" + j).value;
var area = "PersonalDevelopment";
var test = employeeSelected.value;
var entry = new newEntry(statusEntered,
actionsEntered,
targetEntered,
progessEntered,
commentsEntered,
area, test
);
arrayDetails.push(entry);
}
sendToController();
});
function sendToController() {
$.ajax({
type: "POST",
url: '#Url.Action("Save", "OneToOne", "EmpList")',
contentType: "application/json; charset=utf-8",
datatype: JSON,
data: JSON.stringify({ methodParam: arrayDetails }),
traditional: true
});
}
});

searching specific html table column

hello can someone help me with this. the search is working
but how can i exclude the last column to be searched?
i have three columns, first name, lastname and email.
what i want is to search using the two columns only. and exclude the column email when searching. thank you
this is my javascript code
<script type="text/javascript">
function doSearch() {
var searchText = document.getElementById('searchTerm').value;
var targetTable = document.getElementById('report');
var targetTableColCount;
//Loop through table rows
for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++ ) {
var rowData = '';
//Get column count from header row
if (rowIndex == 0) {
targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
continue; //do not execute further code for header row.
}
//Process data rows. (rowIndex >= 1)
for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) {
var cellText = '';
if (navigator.appName == 'Microsoft Internet Explorer')
cellText = targetTable.rows.item(rowIndex).cells.item(colIndex).innerText;
else
cellText = targetTable.rows.item(rowIndex).cells.item(colIndex).textContent;
rowData += cellText;
}
// Make search case insensitive.
rowData = rowData.toLowerCase();
searchText = searchText.toLowerCase();
//If search term is not found in row data
//then hide the row, else show
if (rowData.indexOf(searchText) == -1)
targetTable.rows.item(rowIndex).style.display = 'none';
else
targetTable.rows.item(rowIndex).style.display = 'table-row';
}
}
</script>
and this is my html code
<input id="searchTerm" class="form-control" placeholder="Enter text" onkeyup="doSearch()">
<table id="report" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
</tr>
</tbody>
</table>
i have another question. i added an expandable row on my html table
and now the search doesnt give the desired output. example when i search for a value that are not on the html table it just remove the first row and show the rest of the row. which is not the correct output.
<table id="report" class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr><td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr><td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr><td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td>
</tr>
</tbody>
</table>
sir roman after integrating you're code to mine. the search is now working as expected. but when the searchterm input is empty and i press backspace on it. it became like this
https://jsfiddle.net/t6xg97uo/
I believe this should answer your issue. I am simply adjusting how many columns you are searching:
for (var colIndex = 0; colIndex < (targetTableColCount-1); colIndex++) {
Here is an example:
http://codepen.io/anon/pen/PNWNmL
Update
Ok, I am not sure this is the right fix for what you are looking for, but I just commented out the code that is causing that button to be revealed when backspacing. Here is what I did:
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr>
<!-- <td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td> -->
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr>
<!-- <td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td> -->
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july#example.com</td>
<td>
<div class="arrow"><a id="menu-toggle" href="#" ><i class="glyphicon glyphicon-plus-sign"></i></a></div>
</td>
</tr>
<tr>
<!-- <td colspan="4">
<button type="button" class="btnview btn btn-xs btn-warning" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>View
</button>
</td> -->
</tr>
</tbody>
And here is a jsfiddle:
https://jsfiddle.net/t6xg97uo/1/
Solution including you additional requirement(with an expandable row within a table):
- replace your nested for loop(through row columns) as shown below:
(you should also skip rows which have only one cell(td) from processing)
...
var rowCells = targetTable.rows.item(rowIndex).cells, cellsLen = rowCells.length;
if (cellsLen > 1) {
for (var colIndex = 0; colIndex < 2; colIndex++) {
var cellText = '';
if (targetTable.rows.item(rowIndex).cells.item(colIndex)) {
cellText = rowCells.item(colIndex)[(navigator.appName == 'Microsoft Internet Explorer')? "innerText" : "textContent"];
}
rowData += cellText;
}
}
// Make search case insensitive.
rowData = rowData.toLowerCase().trim();
searchText = searchText.toLowerCase();
//If search term is not found in row data
//then hide the row, else show
if (cellsLen > 1) {
if (searchText && rowData.indexOf(searchText) === -1) {
targetTable.rows.item(rowIndex).style.display = 'none';
} else {
targetTable.rows.item(rowIndex).style.display = 'table-row';
}
}
...

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