How to use onchange event? - javascript

This is my code where if i put quantity then it will calculate it and show it in total amount. my problem is that if i change my quantity in between process my total amount is not change.
How to do it onchange quantity total amount have to different
<script>
function valid(obj)
{
var frm=document.getElementById("frm");
var qty=parseInt(document.getElementById("quantity").value);
var price=parseInt(obj.value);
var total=parseInt(document.getElementById("total").value);
if(isNaN(total))
{
total=0;
}
if(obj.checked==true)
{
total=total+(qty*price);
document.getElementById("total").value=total;
}
else
{
total=total-(qty*price);
document.getElementById("total").value=total;
}
/*for(var i=0;i<frm.length;i++)
{
if(frm[i].type=="checkbox")
{
if(frm[i].checked==true)
{
total=total+(parseInt(frm[i].value)*qty);
}
}
}*/
document.getElementById("total").value=total
}
</script>
<form action="abc.html" method="post" id="frm" onsubmit="return valid(this);">
<table>
<tr>
<th colspan="2">Qualification</th>
</tr>
<tr>
<td><input type="checkbox" name="check_list[]" value="1000" onClick="valid(this);" /></td><td>BCA</td>
<td><input type="checkbox" name="check_list[]" value="2000" onClick="valid(this);" /></td><td>MCA</td>
</tr>
<tr>
<td><input type="checkbox" name="check_list[]" value="1200" onClick="valid(this);" /></td><td>BBA</td>
<td><input type="checkbox" name="check_list[]" value="1000" onClick="valid(this);" /></td><td>MBA</td>
</tr>
<tr>
<td colspan="2"><input type="text" name="quantity" id="quantity" placeholder="Quantity"></td>
</tr>
<tr>
<td colspan="2"><input type="text" name="total" id="total" value="" placeholder="Total"></td>
</tr>
<tr>
<td colspan="2"><input type="button" onClick="valid();" name="submit" value="Send" /></td>
</tr>
</table>
</form>

Define var isFormSubimited = false;
Set isFormSubimited = true in valid function.
Add "onchange='onQuantityChange()'" to quantity input element.
Add following function.
function onQuantityChange()
{
if(isFormSubimited && $("input[type='checkbox']:checked").length > 0)
{
//var _form = document.getElementById('frm');
//_form.submit();
valid();
}
}

Related

How to calculate total sum of checkbox values depend on quantity in textbox

I have the following table
<table>
<tr style="background-color: silver;">
<th>Check it</th>
<th>Estimate item</th>
<th>Quantity</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="checkbox" value="450" /></td>
<td>Remove Tile</td>
<td><input type="text" value="1"></td>
<td>$450</td>
</tr>
<tr>
<td><input type="checkbox" value="550" /></td>
<td>Remove Tub</td>
<td><input type="text" value="1"></td>
<td>$550</td>
</tr>
<p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>
Table example
I found how to calculate the sum of checkboxes values:
<script>
$(document).ready(function () {
var $inputs = $('input[type="checkbox"]')
$inputs.on('change', function () {
var sum = 0;
$inputs.each(function() {
if(this.checked)
sum += parseInt(this.value);
});
$("#price").val(sum);
});
});
</script>
The question is:
If user will update the quantity in textbox, i need to update the total.
I want it to work in two ways: quantity changed before or after checkbox has been checked.
So the value in "Cost" column is equal to checkbox value. I do not want to modify "Cost" column. I need total to be shown at the bottom of the table in "textbox with id="price" textbox.
Case:
User checked the first checkbox #price should be updated with 450.
User checked the second checkbox #price should benow 1000.
User changed the quantity to 2 in the row with the first checkbox.Now #price should be updated to 1450
Thanks in advance!
To achieve this you should loop through the table body's row for that use the code as
$('table tbody tr').each(function()
{
//do something
});
and then find the checkbox in that row. You can check if the check box is checked by using $tr.find('input[type="checkbox"]').is(':checked') this code. It will find a check box in the row and it will check whether it is checked or not.
var $columns = $tr.find('td').next('td').next('td'); This code is used to retrieve the column Quantity.
We call the function calculateSum() to calculate the sum coast of checked rows in both textbox change event and checkbox change event.
$(document).ready(function() {
function calculateSum(){
var sumTotal=0;
$('table tbody tr').each(function() {
var $tr = $(this);
if ($tr.find('input[type="checkbox"]').is(':checked')) {
var $columns = $tr.find('td').next('td').next('td');
var $Qnty=parseInt($tr.find('input[type="text"]').val());
var $Cost=parseInt($columns.next('td').html().split('$')[1]);
sumTotal+=$Qnty*$Cost;
}
});
$("#price").val(sumTotal);
}
$('#sum').on('click', function() {
calculateSum();
});
$("input[type='text']").keyup(function() {
calculateSum();
});
$("input[type='checkbox']").change(function() {
calculateSum();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sum" type="button">Calculate</button><br/>
<table>
<tr style="background-color: silver;">
<th>Check it</th>
<th>Estimate item</th>
<th>Quantity</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="checkbox" name="chck" value="450" /></td>
<td>Remove Tile</td>
<td><input type="text" name="qnty" value="1"></td>
<td>$450</td>
</tr>
<tr>
<td><input type="checkbox" class="chck" value="550" /></td>
<td>Remove Tub</td>
<td><input type="text" name="qnty" value="1"></td>
<td>$550</td>
</tr>
</table>
<p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>
<div class="serve" id="service">
<form action="" id="roomform" onsubmit="return false">
<div class="order">
<fieldset>
<legend>Tell us where to clean:</legend>
<p>
<input value="30" type="checkbox" id="myCheck" class="sum" name="myCheck" oninput="x.value=parseInt(bedroom.value)*30.00"/>
<label for="sleeping" class="contain">Bedrooms (P30/room) </label>
<input type="number" id="a" class="room" value="1" min="1" max="20" onchange="calculateTotal()"/>
Total: P <span id="costPrice"> </span
</p>
<p>
<input value="20" type="checkbox" id="myCheck" class="sum" name="myCheck1" onclick="calculateTotal()" />
<label for="sitting" class="contain">Sitting room (P20/room)</label>
<input type="number" class="room" id="a" value="1" min="1" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
<input value="20" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Dining room (P20/room)</label>
<input type="number" class="room" id="a" value="1" min="1" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
Extra services:</p>
<p>
<input value="15" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Carpet Cleaning (P 15/room)</label>
<input type="number" class="room" id="a" value="0" min="0" max="20" />
Total: P <output type="number" ></output>
</p>
<p>
<input value="3" type="checkbox" id="myCheck" class="sum" onclick="calculateTotal()" />
<label class="contain">Window Cleaning (P 3/room)</label>
<input type="number" class="room" id="a" value="0" min="0" max="20" />
Total: P <output type="number" ></output>
</p>
<div class="grandPrice" >
Grand Total Price: P<span id="grandTotal">0</span>
</div>
</fieldset>
</div>
</form>
<script>
// When a checkbox is clicked
/*$('#order input[type=checkbox]').click(function() {
// Get user input and set initial variable for the total
inputBox = parseInt($('#a').val());
bedroomPrices = 0;
// If it's checked, add the current value to total
if($(this).prop('checked'))
{
thisValue = parseInt($(this).val());
bedroomPrices = bedroomPrices + thisValue;
}
// Output the total checkbox value multipled against user input
$('#costPrice').html(bedroomPrices * inputBox);
});*/
var checkbox = document.getElementsByClassName('sum'),
inputBox = document.getElementById('a'),
GrandTotal = document.getElementById('grandTotal');
//"(this.checked ? 1 : -1);" this sees if checkbox is checked or unchecked by adding or subtracting it (1 :-1)
//make sure that each checkbox total is added if its checked
for (var i=0; i < checkbox.length; i++) {
checkbox[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
grandTotal.innerHTML = parseFloat(grandTotal.innerHTML) + add
}
}
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="indent_list">
<table border="1">
<thead>
<tr>
<th>rate</th>
<th>quantity</th>
<th>coltotal</th>
</tr>
</thead>
<body>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="1"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="2"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
<tr>
<td><input type="text" id="val" class="rate" value="10"></td>
<td><input type="text" id="val" class="quantity" value="2"></td>
<td><input type="text" id="val" class="coltolal" value=""></td>
</tr>
</body>
<tfoot>
<tr>
<th class="rateRow"></th>
<th class="quantityRow"></th>
</tr>
<tr>
<th colspan="2" class="totalRow"></th>
</tr>
</tfoot>
</table>
</div>
> button
<input type="checkbox" class="btn btn-info checkbox" onclick="calculateCheck()">
<input type="button" class="btn btn-info" onclick="calculate()" value="Calculate">
> script
<script>
function calculateCheck() {
var check = $('.checkbox').prop('checked');
if (check) {
calculate()
} else {
$('.rateRow').text('');
$('.quantityRow').text('');
$('.totalRow').text('');
}
}
function calculate() {
var rateRow = '';
var quantityRow = '';
var totalRow = '';
var rate = 0;
var quantity = 0;
var total = 0;
// alert(quantitycol);
$('tbody tr').each(function () {
var ratecol = $('td .rate', this).val();
var quantitycol = $('td .quantity', this).val();
var coltotal = ratecol * quantitycol;
$('td .coltolal', this).val(coltotal);
// alert(a);
rate += +$('td .rate', this).val();
quantity += +$('td .quantity', this).val();
total = rate * quantity;
});
rateRow += rate;
quantityRow += quantity;
totalRow = total;
$('.rateRow').text(rateRow);
$('.quantityRow').text(quantityRow);
$('.totalRow').text(totalRow);
}
</script>

How to make limit(error alert) for checked numbers or units sum(JavaScript)?

hi.this is my code.
How can I make limit for checked numbers or units sum?
for ex:if sum is ≤12 and ≥20 show error log(result) when press submit button.
<script type="text/javascript">
function chkcontrol(j)
{
var sum=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.form1.ckb[i].checked){
sum = sum + parseInt(document.form1.ckb[i].value);
}
document.getElementById("msg").innerHTML="Sum :"+ sum;
if(sum >20){
sum = sum - parseInt(document.form1.ckb[j].value);
document.form1.ckb[j].checked = false ;
alert("error:Total of yore choose is more than 20 units")
//return false;
}
document.getElementById("msg").innerHTML="total units :"+ sum;
}
}
</script>
This should solve your problem.
var form = document.forms.myform,
elem = form.elements,
inputVals = document.getElementsByClassName("inputVals");
form.onsubmit = function(event){
event.preventDefault();
var totalSum = 0;
for(var i = 1; i <= inputVals.length; i++) {
var input = document.getElementById("value" + i)
if (input.checked) {
totalSum += parseInt(input.value);
}
}
if (totalSum < 12 || totalSum > 20) {
alert("error:Total of your choise is more than 20 or less 12 units")
}
else {
document.getElementById("msg").innerHTML="total units :" + totalSum;
}
}
.center{text-align:center;margin-top:1em;}
<form name="myform" actopm="/echo/html/" method="post">
<table>
<tr>
<th>1</th>
<td><input class="inputVals" value=1 type="checkbox" id="value1" placeholder="input value"/></td>
</tr>
<tr>
<th>2</th>
<td><input class="inputVals" value=2 type="checkbox" id="value2" placeholder="input value"/></td>
</tr>
<tr>
<th>3</th>
<td><input class="inputVals" value=3 type="checkbox" id="value3" placeholder="input value"/></td>
</tr>
<tr>
<th>4</th>
<td><input class="inputVals" value=4 type="checkbox" id="value4" placeholder="input value"/></td>
</tr>
<tr>
<th>5</th>
<td><input class="inputVals" value=5 type="checkbox" id="value5" placeholder="input value"/></td>
</tr>
<tr>
<th>6</th>
<td><input class="inputVals" value=6 type="checkbox" id="value6" placeholder="input value"/></td>
</tr>
<tr>
<th>7</th>
<td><input class="inputVals" value=7 type="checkbox" id="value7" placeholder="input value"/></td>
</tr>
<tr>
<th>8</th>
<td><input class="inputVals" value=8 type="checkbox" id="value8" placeholder="input value"/></td>
</tr>
</table>
<div class="center">
<input type="submit" value="submit"/>
</div>
</form>
<div id="msg">
</div>

How to update value based on other input box dynamically using jQuery?

I'm trying to make a shopping cart.
Where I have list of products which has different price.
Now when i tried to change the quantity the price should change based on quantity as well as the total one.
But the problem i'm facing is using the below code when i tried to change the quantity, price get updated but the others also get updated as well though i didn't change the Quantity.
Then total one doesn't show the appropriate total
$(".quantity").change(update);
function update() {
$(".quantity").each(function() {
var qty = Number($(this).val());
var net = document.getElementById("net_price").value;
var total = qty * net;
$('.total').html("$" + total);
$(".grandTotal").text(calculateSum());
});
function calculateSum() {
var sum = 0;
$(".total").each(function() {
var value = $(this).val();
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
return sum;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="qty table-default">
<input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" /></td>
<td class="total_price table-default total"></td>
<td><input type="hidden" id="net_price" value="">45</td>
<td class="grandTotal"></td>
</tr>
</table>
Anyone please help me to find the soultion
If i understand you correctly this may help you
$('body').on('change', ".quantity", update);
function update() {
var qty = parseInt($(this).val());
var net = parseFloat($(this).parents('tr').find(".net_price").val());
var total = qty * net;
$(this).parents('tr').find(".total_price").text("$" + total);
$(".grandTotal").text('$' + calculateSum());
function calculateSum() {
var sum = 0;
$(".total_price").each(function() {
var value = $(this).text().replace('$', '');
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
return sum;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="qty table-default">
<td><input type="text" readonly class="net_price" value="25"></td>
<td><input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" /></td>
<td class="total_price table-default total"></td>
</tr>
<tr>
<td class="qty table-default">
<td><input type="text" readonly class="net_price" value="25"></td>
<td><input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" /></td>
<td class="total_price table-default total"></td>
</tr>
<tr>
<td class="qty table-default">
<td><input type="text" readonly class="net_price" value="25"></td>
<td><input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" /></td>
<td class="total_price table-default total"></td>
</tr>
<tr>
<td colsapn="3" class="grandTotal"></td>
</tr>
</table>
Performance Improvement
A performance improvement of above code by extracting calculateSum externally to avoid recreation of same function again and again while calling update method
$('body').on('change', ".quantity", update);
function calculateSum() {
var sum = 0;
$(".total_price").each(function() {
var value = $(this).text().replace('$', '');
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
return sum;
}
function update() {
var qty = parseInt($(this).val());
var net = parseFloat($(this).parents('tr').find(".net_price").val());
var total = qty * net;
$(this).parents('tr').find(".total_price").text("$" + total);
$(".grandTotal").text('$' + calculateSum());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="qty table-default">
<td><input type="text" readonly class="net_price" value="25"></td>
<td><input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" /></td>
<td class="total_price table-default total"></td>
</tr>
<tr>
<td class="qty table-default">
<td><input type="text" readonly class="net_price" value="25"></td>
<td><input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" /></td>
<td class="total_price table-default total"></td>
</tr>
<tr>
<td class="qty table-default">
<td><input type="text" readonly class="net_price" value="25"></td>
<td><input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" /></td>
<td class="total_price table-default total"></td>
</tr>
<tr>
<td colsapn="3" class="grandTotal"></td>
</tr>
</table>
You are setting the HTML value for element which is $ concatenated with value but while retrieving the value, you are using .val() method. To get the text from the element, use .text method instead.
As value is prefixed with $, we can not use it for manipulations hence .data method is used to store numerical value in data for particular element.
jQuery.data('key') is used to retrieve the value.
$(".quantity").change(update);
function update() {
$(".quantity").each(function() {
var qty = Number($(this).val());
var net = 10; //Static value is considered
var total = qty * net;
var totalElem = $('.total');
totalElem.html("$" + total);
totalElem.data("value", total);
$(".grandTotal").text(calculateSum());
});
function calculateSum() {
var sum = 0;
$(".total").each(function() {
var value = $(this).data('value');
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
return sum;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td class="qty table-default">
<input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" />
</td>
<td class="total_price table-default total"></td>
<td class="grandTotal"></td>
</tr>
</table>
$(".quantity").change(update);
function update() {
// Cell Variables
var $qty = $(this),
$row = $qty.closest('tr'),
$total = $row.find('.total');
// Number Variables
var qty = Number($qty.val()),
price = $row.find('.price').val(),
total = qty * price;
// Fill Values
$total.html("$" + total);
$('.grandTotal').text('$' + calculateSum());
}
function calculateSum() {
var sum = 0;
$('.total').each(function() {
var strTotal = $(this).text();
var total = parseFloat(strTotal.replace(/^\D+/g, ''));
if (!isNaN(total))
sum += total;
});
return sum;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
<th>Grand Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="qty table-default">
<input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" />
</td>
<td><input type="hidden" class="price" value="45" />$45</td>
<td class="total_price table-default total"></td>
<td class="grandTotal"></td>
</tr>
<tr>
<td class="qty table-default">
<input type="number" class="quantity" value="" name="qty" maxlength="3" max="999" min="1" />
</td>
<td><input type="hidden" class="price" value="10" />$10</td>
<td class="total_price table-default total"></td>
<td class="grandTotal"></td>
</tr>
</tbody>
</table>

Using the same jQuery in multiple operations

I have a small question and I hope someone can help me with it :D
I’m trying to create a product table, in which a user just add the quantity of a product and the jquery makes the multiplication to its value and gives the result
I already made this, and it works well:
<script>
$(document).ready(function(){
$('#quantity_1').keyup(function(){
var price_1 = $("#price_1").val();
var quantity_1 = $("#quantity_1").val();
quantity_1 = quantity_1.replace(/[^0-9]+/g, '');
$("#quantity_1").val(quantity_1);
var total_1 = price_1 * quantity_1;
$( "#total_1" ).val( total_1.toFixed(2) );
});
});
</script>
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
</table>
Working demo here:
http://jsfiddle.net/EnterateNorte/9kswL0gf/
But I would like to be able to add more than one line, like so:
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Name 1</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
<tr>
<td>Name 5</td>
<td><input type="hidden" name="product[5][price]" id="price_5" value="10.00" />23.00</td>
<td><input type="text" name="product[5][quantity]" id="quantity_5" /></td>
<td><input type="text" name="product[5][total]" id="total_5" value="0" /></td>
</tr>
<tr>
<td>Name 3</td>
<td><input type="hidden" name="product[3][price]" id="price_3" value="130.00" />10.00</td>
<td><input type="text" name="product[3][quantity]" id="quantity_3" /></td>
<td><input type="text" name="product[3][total]" id="total_3" value="0" /></td>
</tr>
<tr>
<td>Name 4</td>
<td><input type="hidden" name="product[4][price]" id="price_4" value="12.00" />10.00</td>
<td><input type="text" name="product[4][quantity]" id="quantity_4" /></td>
<td><input type="text" name="product[4][total]" id="total_4" value="0" /></td>
</tr>
</table>
And if it isn’t to much trouble, I would be awesome if it would SUM all the totals and show a gran total at the end of the table :)
Use:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var price = $(this).parent().prev().find('input').val();
var quantity = $(this).val();
var total = price * quantity;
$(this).parent().next().find('input').val( total.toFixed(2) );
});});
Working Demo
Update: For showing Grand Total
var sum = 0;
//iterate through each textboxes and add the values
$('[name*=total]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseInt(this.value);
}
});
Working Demo
What you can do is to find the elements using their relative position instead of hard coded ids
$(document).ready(function () {
$('input[id^="quantity_"]').keyup(function () {
var $tr = $(this).closest('tr');
var price = $tr.find('input[id^="price_"]').val();
var quantity = this.value;
var total = (price * quantity) || 0;
$tr.find('input[id^="total_"]').val(total.toFixed(2));
});
});
Demo: Fiddle
I've updated your code in Fiddle. You need to change in your markup a bit.
<tr>
<td>Product Name</td>
<td><input type="hidden" class="price" ... />10</td>
<td><input type="text" class="quantity" ... /></td>
<td><input type="text" class="total" ... /></td>
</tr>
$(document).ready(function(){
$('.quantity').keyup(function(){
var parent = $(this).closest("tr");
var price = $(".price", parent).val();
var quantity = $(".quantity", parent).val();
var total = price * quantity;
$(".total", parent).val(total.toFixed(2));
});
});
I would recommend you to use common class
HTML:
<tr>
<td>Name 5</td>
<td>
<input type="hidden" class="price" value="10.00" />10.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
<tr>
<td>Name 3</td>
<td>
<input type="hidden" class="price" value="130.00" />130.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
Script:
$('.quantity').keyup(function () {
var tr = $(this).closest('tr');
var price = tr.find('.price').val();
var quantity = $(this).val();
var total = price * quantity;
tr.find('.total').val(total.toFixed(2));
});
DEMO
Modify your table:
<table border="1" cellpadding="5px" cellspacing="0" id='table' >
<!-- your rows with inputs -->
<tr>
<td>
<input id='totalSum' value='0' type='text' />
</td>
</tr>
</table>
Make all your 'total' inputs readonly by adding 'readonly' attribute.
js code:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var total = 0;
$('#table tr').each(function(i,item){
var price = parseFloat($(item).find('[name*=price]').val().replace(',','.'));
var quantity = parseInt($(item).find('[name*=quantity]').val());
if(!isNaN(price) && !isNan(quantity)){
total += price*quantity;
}
});
$("#totalSum").val(total.toFixed(2));
});
});

OnBeforeUnload if qty inputs are differents of 0

I have html table like this :
<table border="1">
<tr>
<td>Prod name </td>
<td>Qty</td>
<td>Add to cart </td>
</tr>
<tr>
<td>product 1 </td>
<td><input name="super_group[961]" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
<td><input type="submit" name="Submit" value="Envoyer" /></td>
</tr>
<tr>
<td>product 2 </td>
<td><input name="super_group[962]" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
<td><input type="submit" name="Submit2" value="Envoyer" /></td>
</tr>
</table>
and I want to avoid that user quit the page when there is a quantity typed in the qty input fields.
(I have to show a message only if a quantity field is not 0).
With jQuery you could:
$(window).bind('beforeunload', function(e) {
var prompt = false;
$('input.qty').each(function(i, input) {
if ($(input).val() != '0') {
prompt = true;
}
});
if (prompt) {
return e.returnValue = 'Some warning message';
}
});
However https://developer.mozilla.org/en/DOM/window.onbeforeunload
Note that in Firefox 4 and later the returned string is not displayed to the user. See Bug 588292.
Added AJAX when non-zero - NOT tested
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(window).bind('beforeunload', function(e) { // thanks #Ghostoy for the jquery version of this
var nonzero = false;
$(".qty").each(function() { // selector assuming input with class qty
if (this.value>0) {
nonzero=true;
return false; // leave the each
}
});
if (nonzero) return "You have unsaved changes";
});
$("input[id^='sg_']").each(function() {
$(this).bind("keyup", function() {
var disabled = isEmpty(this.value);
$("#bt_"+this.id.split("_")[1]).attr("disabled",disabled);
});
});
$("input[id^='bt_']").each(function() {
var itemId=this.id.split("_")[1]
var val = $("#sg_"+itemId).val()
$(this).attr("disabled",isEmpty(val);
$(this).click(function() {
$.get("add_to_cart.php?item="+itemId+"&qty="+$("#sg_"+itemId).val();
});
});
function isEmpty(val) {
return isNaN(val() || val=="" || val==null;
}
</script>
</head>
<body>
<form action="">
<table border="1">
<tr>
<td>Prod name </td>
<td>Qty</td>
<td>Add to cart </td>
</tr>
<tr>
<td>product 1 </td>
<td><input name="super_group[961]" id="sg_961" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
<td><input type="button" id="bt_961" value="Envoyer" /></td>
</tr>
<tr>
<td>product 2 </td>
<td><input name="super_group[962]" id="sg_962" type="text" class="input-text qty" title="Qty" value="0" size="5" maxlength="12"></td>
<td><input type="button" id="bt_962" value="Envoyer" /></td>
</tr>
</table>
</form>
</body>
</html>

Categories

Resources