OnBeforeUnload if qty inputs are differents of 0 - javascript

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>

Related

verticle focus on textbox

i need to focus textbox in verticle by press enter key
first row and then second row then third row
here My script,
$(document).ready(function() {
$(".vertical_row1").keypress(function(event) {
if(event.keyCode == 13) {
textboxes = $("input.vertical_row1");
debugger;
currentBoxNumber = textboxes.index(this);
if (textboxes[currentBoxNumber + 1] != null) {
nextBox = textboxes[currentBoxNumber + 1]
nextBox.focus();
nextBox.select();
event.preventDefault();
return false
}
}
});
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td><input class="vertical_row1" type="text" name="" value="" placeholder=""></td>
<td><input class="vertical_row2" type="text" name="" value="" placeholder=""></td>
</tr>
<tr>
<td><input class="vertical_row1" type="text" name="" value="" placeholder=""></td>
<td><input class="vertical_row2" type="text" name="" value="" placeholder=""></td>
</tr>
<table>
(function ($) {
$.fn.formNavigation = function () {
$(this).each(function () {
// Events triggered on keydown (repeatable when holding the key)
$(this).find('input').on('keydown', function(e) {
// Vertical navigation using tab as OP wanted
if (e.which === 13 && !e.shiftKey) {
// navigate forward
if ($(this).closest('tr').next().find('input').length>0) {
// when there is another row below
e.preventDefault();
$(this).closest('tr').next().children().eq($(this).closest('td').index()).find('input').focus();
} else if ($(this).closest('tbody').find('tr:first').children().eq($(this).closest('td').index()+1).find('input').length>0) {
// when last row reached
e.preventDefault();
$(this).closest('tbody').find('tr:first').children().eq($(this).closest('td').index()+1).find('input').focus();
}
} else if (e.which === 13 && e.shiftKey) {
// navigate backward
if ($(this).closest('tr').prev().find('input').length>0) {
// when there is another row above
e.preventDefault();
$(this).closest('tr').prev().children().eq($(this).closest('td').index()).find('input').focus();
} else if ($(this).closest('tbody').find('tr:last').children().eq($(this).closest('td').index()-1).find('input').length>0) {
// when first row reached
e.preventDefault();
$(this).closest('tbody').find('tr:last').children().eq($(this).closest('td').index()-1).find('input').focus();
}
}
});
});
};
})(jQuery);
// usage
$('.gridexample').formNavigation();
<!DOCTYPE html>
<html>
<body>
<table class="gridexample">
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</tbody>
<table>
<!-- jQuery needed for this solution -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
</body>
</html>
Try tabIndex
TabIndex MDN
<table>
<tr>
<td><input tabindex="0" class="vertical_row1" type="text" name="" value="" placeholder=""></td>
<td><input tabindex="2" class="vertical_row2" type="text" name="" value="" placeholder=""></td>
</tr>
<tr>
<td><input tabindex="1" class="vertical_row1" type="text" name="" value="" placeholder=""></td>
<td><input tabindex="3" class="vertical_row2" type="text" name="" value="" placeholder=""></td>
</tr>
<table>

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 use onchange event?

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

Get all input values from table excluding first column

I want to alert the input value of each row except the first column.
Here is my code.
<table id="table">
<tr>
<td><input type="text" size="5" value="name"/></td>
<td><input type="text" size="5" value="number"/></td>
<td><input type="text" size="5" value="class"/></td>
</tr>
<tr>
<td><input type="text" size="5" value="bbbbb"/></td>
<td><input type="text" size="5" value="1"/></td>
<td><input type="text" size="5" value="2"/></td>
</tr>
<tr>
<td><input type="text" size="5" value="cccc"/></td>
<td><input type="text" size="5" value="5"/></td>
<td><input type="text" size="5" value="2"/></td>
</tr>
<tr>
<td><input type="text" size="5" value="ddddd"/></td>
<td><input type="text" size="5" value="1"/></td>
<td><input type="text" size="5" value="2"/></td>
</tr>
$(document).ready(function() {
$("#table tr:gt(0) td:gt(0) ").each(function()
{
a=$(this).find('input[type="text"]').val();
alert(a);
});
});
While running this code all value alerted except "bbbb". (ie,ccccc ,dddd alerted.). I only need each rows second one column onwords.
fiddle: https://jsfiddle.net/k1tfo5kb/
This should work:
https://jsfiddle.net/23jcejbm/
$(document).ready(function() {
var $cells = $("#table tr td").not(':first-child'),
$inputs = $cells.find('input[type="text"]');
$.each($inputs, function(){
var value = this.value;
alert(value);
});
});
Here you go: https://jsfiddle.net/pukw0uLz/1/
I changed alert to console.log, much less aggressive. Make sure to open you web console!

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

Categories

Resources