I have here shopping cart using php. I add a script for getting the sum of all input fields. What I need to do is get the sum of all quarter per row. The problem is all of total fields gets the sum value of row. How I can get the sum per row?
<script type="text/javascript">
$('.qtys').blur(function() {
var sum = 0;
$('.qtys').each(function() {
sum += Number($(this).val());
});
$('.qty_total').val(sum);
});
</script>
while($obj = $results->fetch_object())
{
<td><input type="text" name="product_qty" size="1" class="qty_total"/></td>
<td><input type="text" name="qty1st" size="1" class="qtys"/></td>
<td><input type="text" name="qty2nd" size="1" class="qtys"/></td>
<td><input type="text" name="qty3rd" size="1" class="qtys"/></td>
<td><input type="text" name="qty4th" size="1" class="qtys"/></td>
}
The selector $('.qty_total') will give you call the elements having class qty_total but you need only one in the current row. Use the qty_total in the current row. You can get the parent row but $(this).closest('tr') then you can find the the qty_total using find()
Also use $(this).closest('tr').find('.qtys').each instead of $('.qtys').each(function()
Live Demo
Your code
<script type="text/javascript">
$('.qtys').blur(function () {
var sum = 0;
$(this).closest('tr').find('.qtys').each(function () {
sum += Number($(this).val());
});
$(this).closest('tr').find('.qty_total').val(sum);
});
</script>
Check this Demo Fiddle
<script type="text/javascript">
$('.qtys').blur(function() {
var sum = 0;
$(this).closest('tr').find('.qtys').each(function() { //.qtys of current row,
sum += Number($(this).val());
});
$(this).closest('tr').find('.qty_total').val(sum); // total of current row
});
</script>
You need Quarter values of current row. $(this).closest('tr') gives you the <tr> parent of current <td>. So, the selector would update values of current row instead of all the rows which your previous code did.
All your operations need to work on current row being manipulated. .closest('tr') helps in manipulating only the child elements of current row.
Alternative : $(this).parents('tr')
this is the way to do it:
//gets the inputs in the correct row
$(this).parent('tr').children('.qtys').each(function(){
//sums it
totalSum=totalSum+$(this).val();
//puts it in the total input
$(this).parent('tr').children('td:nth-child(3)').children('input').val(totalSum);
});
Related
I have a table with a button that adds 5 rows with cells to the table when clicked. I want to bind an event to cells in the 5th column of the table. All of these cells are named "Count_" followed by the row number. So, the cell in Row 0 is:
<td name="CountCell_0">
<input type="text" name="Count_0">
</td>
And I'm trying to update the input with name Count_X (where X is the row number).
The binding works for the cells that existed on the page originally. However, the event is not triggering for cells that were added with the button.
Here is an example of a cell that was dynamically added:
<td>
<input type="text" name="Count_348">
</td>
Here is my Jquery event:
$(document).ready(
function() {
$(document).on('change','[name^="Count_"]',function() {
console.log('here'); //not triggering on dynamic cell
var cell = $(this).attr('name');
var idx = cell.split('_')[1];
var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
$('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
});
}
);
I think the problem was here [name^="Count_"]' you need a selector so change to this input[name^="Count_"]' and the anonimous function is not performed
$(document).ready(
(function() {
$(document).on('change','input[name^="Count_"]',function() {
console.log('here'); //not triggering on dynamic cell
var cell = $(this).attr('name');
var idx = cell.split('_')[1];
var amount = $(this).val() * $('[name="AvgCost_' + idx + '"]').html();
$('#ExtendedCostCell_' + idx).html(amount.toFixed(2));
});
}());
);
I moved the function outside of the document ready, and it now triggers on the dynamic rows.
I would like to know how to dynamically increase and decrease numbers in JavaScript.
The users buys an item and I have a input field "quantity" with a number and two buttons: One to add and another to remove.
My code is the following
<td class="quantity">
-
<input type="text" id="purchase_quantity" min="1" max="99" delta="0" cost="<?php echo$poupa ?>" name="purchase_quantity" value="1" />
<a href="#" class="addItem" >+</a>
</td>
How can I have it decrease the number of the input field when I click on the "-" and increase the number of the input field when clicking on the "+"?
var input = document.getElementById("YOUR_INPUT_ID");
function minus(){
var num = +input.value;//+ for convert from string to number
num--;
input.value = num;
}
function plus(){
var num = +input.value;//+ for convert from string to number
num++;
input.value = num;
}
http://jsfiddle.net/VY9tE/
One more example with your html form and with check count(0..99):
http://jsfiddle.net/VY9tE/2/
decrease:
-
increase
+
Assuming you can use jquery since you have it tagged.
Markup (changed the ID on the text input to a class):
<td class="quantity">
-
<input type="text" class="purchase_quantity" min="1" max="99" delta="0" cost="" name="purchase_quantity" value="1" />
+
</td>
JavaScript (uses jQuery):
$(function() {
$('.removeItem').click(function() {
// Find the appropriate quantity input
var target = $(this).siblings('.purchase_quantity');
// Get the current quantity
var currentQuantity = $(target).val();
// Not allowed to go below zero
if (currentQuantity > 0) {
// Update input with decreased quantity
$(target).val(--currentQuantity);
}
});
$('.addItem').click(function() {
// Find the appropriate quantity input
var target = $(this).siblings('.purchase_quantity');
// Get the current quantity
var currentQuantity = $(target).val();
// Update input with increased quantity
$(target).val(++currentQuantity);
});
});
See it in action.
I have a problem.
an array would return me some dynamically data from it.
<?php
foreach($ItemArray as $key => $value) {
echo '
<tr><td height="30" valign="middle">'.$value['nr'].'</td>
<td valign="middle">'.$value['product'].'</td>
<td valign="middle">'.$value['describe'].'</td>
<td valign="middle" id="price_'.$key.'">'.$value['price'].'</td>
<td valign="middle" class="box_darker" id="amount_'.$key.'">
<input name="Field_Amount_'.$key.'" id="Field_Amount_'.$key.'" class="Field_Amount" type="text" /></td>
<td valign="middle" id="price_'.$key.'">$key</td></tr>'; }
;?>
Now I would test if the value returns me the right one when click on belong field (td/price)
$(document).on('click', '[id^=price_]', function(){
var Amount = $('[id^=Field_Amount_]').val();
alert(Amount);
});
But nevermind wich field (td/price) in each row I click, it alert me only the value from first row! maybe because the data loads dynamically?
Sorry for that poor English.
That's because you perform your second search on the global scope as well, and val() will return the value from the first element. Use $(this).parent().find() instead:
$(document).on('click', '[id^=price_]', function(){
var Amount = $(this).parent().find('[id^=Field_Amount_]').val();
alert(Amount);
});
Alternately, you should also be able to use .closest():
$(document).on('click', '[id^=price_]', function(){
var Amount = $(this).closest('[id^=Field_Amount_]').val();
alert(Amount);
});
Your trigger event is working fine since every row reacts to the click.
What's "wrong" is the selector for the Field_amount. This always selects the first Field_Amount_ because the selector is working on the whole page.
Try using the .closest() function:
$(document).on('click', '[id^=price_]', function(){
var Amount = $(this).closest('[id^=Field_Amount_]').val();
alert(Amount);
});
Try This
$(document).on('click', '[id^=price_]', function(){
var key = $(this).attr('id').split('price_');
var amount = $("#Field_Amount_"+key[1]).val();
});
I have php code that creates a table. For each item on the purchase order a new row is created and populated. The goal is when the purchase order is edited it gets posted back and saved in the database. Everything is working except my jQuery code will only iterate over the first row for however many rows I have. (So if I have three rows it will print the first rows cartid three times.)
Sorry if things look messy.
PHP Code:
<?php while($row = mysql_fetch_array($itemsquery)){?>
<tr class="item-row" id="<?php echo $row['cart_id']?>">
<td class="item-name"><div class="delete-wpr"><textarea><?php echo $row['on0'];?> <?php echo $row['itemname'];?></textarea><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><textarea class="cartid"><?php echo $row['cart_id'];?></textarea></td>
<td><textarea class="cost" class="text-input" type="text"><?php echo $row['itemprice'];?></textarea></td>
<td><textarea class="qty" type="text" name="name"><?php echo $row['quantity'];?></textarea></td>
<td><span class="price" type="text">$<?php
$linecost = $row['quantity'] * $row['itemprice'];
echo $linecost;?></span></td>
</tr>
<?php }?>
jQuery statement to see what it has grabbed:
$(document).ready(function(){
$(".item-row").change(function() {
$((".cartid")).each(function(){
row = {
cartid: $(".cartid").val()
}
alert(row.cartid);
performAjaxSubmission();
})
});
It looks like you just have your selectors mixed up. You are wanting to iterate over each of the rows, but your selector is referencing $(".cartid"), which would always return the first result ever time.
This should fix your problem:
$(document).ready(function(){
$(".item-row").change(function() {
$(".item-row").each(function(){
var rowContext = $(this);
var row = {
cartid: $(".cartid", rowContext).val()
}
alert(row.cartid);
performAjaxSubmission();
});
});
You have extra () in your .cartid selector.
$(document).ready(function(){
$(".item-row").change(function() {
$(".cartid").each(function(){
row = {
cartid: $(".cartid").val()
}
alert(row.cartid);
performAjaxSubmission();
})
});
Also, shoudn't you be looping trough .item-row instead of .cartid?
You're iterating like this:
$(".cartid").each(function(){
row = {
cartid: $(".cartid").val()
}
Seems like you should be doing
$(".cartid").each(function(){
row = {
cartid: $(this).val()
}
Haven't checked the rest of the code.
EDIT:
$(".cartid").each(function(){
var cart = $(this);
row = {
cartid: cart.val()
}
i am working in a code igniter. i have a form which contain three input boxes in a row . ..i put them in a for loop which is less then five ..so now my form has five rows with three input boxes in a row .. now what i am doing write now i am adding the values of two input boxes and displaying in 3rd input box .. now what i want to do is when every "total"(3rd input box) is filled .. then i am gonna add all the totals and then display all the totals in last box which i display at the bottom ..
here is my view
<td><input type="text" id = "price_<?php echo $i ?>"
onkeyup='addition(<?php echo "$i"?>)'>
</td>
<td> <input type="text" id = "quantity_<?php echo $i ?>" onkeyup='addition(<?php echo "$i"?>)'>
</td>
<td><input type="text" id = "total_<?php echo $i ?>">
</td>
<?php echo form_input($subtotal)?></td> // here i want to display sum of all the totals
here is my javascript..this function is multiplying the price and quantity ..i mean first and 2nd input box and then displaying in the 3rd box ..
function addition (obj)
{
var subtotal = 0;
var num1=parseInt($('#price_'+obj).val());
var num2=parseInt($('#quantity_'+obj).val());
var num4=parseInt($('#total_'+obj).val());
if ($('#price_'+obj).val() !='' && $('#quantity_'+obj).val() !='')
{
var num3=num1*num2;
$('#total_'+obj).val(num3);
}
else
{
$('#total_'+obj).val('');
}
}
i have uploaded the image also ..
I see that you use jQuery, I have modified your code a bit to use jQuery better. You can see the demo at JsBIN
The idea is lock all "total" cell, when you update one "total" cell by calculating the result. Sum all "total" cell to the "grand-total" cell. I listen on the "keyup" event.
Here is jsFiddle example: http://jsfiddle.net/Ner7M/2/
Code of interest:
var table = $('table');
// nth-child is 1-based, not 0
function totalColumn(table, idx) {
var total = 0;
var tds = $('table')
.find('tr td:nth-child(' + idx + ') input')
.each(function() {
total += parseInt($(this).val());
});
return total;
}
totalColumn(table, 3);