Reputation: 566
I am working with some number of Number fields on a table.The table contains Item Name, Unit Price and Number Filed which is Quantity.Each Time Amount is increased or decreased i want an array of products/items which will contain item name
, item unit price
, item Amount
, total price of that item
.
items =
[
['Name', '5', '2', '10'],
['Name2', '15', '2', '30'],
]
If amount is zero
Then that item will not take place in the array.
jQuery(document).ready(function() {
jQuery(document).on('input', '.se-ticket-qty', function() {
var items = GetItems();
// jQuery('input#items').val(items);
console.log(items);
});
function GetItems() {
jQuery(".se-ticket-qty").each(function(index) {
var items = [];
var item_name = jQuery(this).data('name');
var unit_price = parseFloat(jQuery(this).data('unit-price'));
var amount = parseFloat(jQuery(this).val());
var totalPrice = unit_price * amount;
items = [item_name, unit_price, amount, totalPrice];
});
return items;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Front Row</th>
<td><span class="se-curency">$ </span>5</td>
<td>
<input min="0" data-name="Front Row" data-unit-price="5" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<th>VIP Seat</th>
<td><span class="se-curency">$ </span>10</td>
<td>
<input min="0" data-name="VIP Seat" data-unit-price="10" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
</table>
Upvotes: 0
Views: 45
Reputation: 133403
You are reassigning items
to a new Array
.push()
method to populate new array ElementunitPrice
for dashed keys when using .data()
method.Code
function GetItems() {
var items = []; //Initialize
jQuery(".se-ticket-qty").each(function(index) {
var item_name = jQuery(this).data('name');
var unit_price = parseFloat(jQuery(this).data('unitPrice'));
var amount = parseFloat(jQuery(this).val());
//Add condtion for zero
if (amount > 0) {
var totalPrice = unit_price * amount;
items.push([item_name, unit_price, amount, totalPrice]); //Use push
}
});
return items;
}
jQuery(document).on('input', '.se-ticket-qty', function() {
var items = GetItems();
console.clear();
console.log(items);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Front Row</th>
<td><span class="se-curency">$ </span>5</td>
<td>
<input min="0" data-name="Front Row" data-unit-price="5" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<th>VIP Seat</th>
<td><span class="se-curency">$ </span>10</td>
<td>
<input min="0" data-name="VIP Seat" data-unit-price="10" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
</table>
Upvotes: 2