Here is what I'm doing.
I have a set of divs. Each set of divs can contain a section header and a list of items. Each item has a price associated with it. So item 1 under section Demolition has a price of 150.00. Item 2 under section Demolition has a price of 200.00. Next to each item is an input field that the user can type in a numeric value. That value is then multiplied by the item price. So next to item 1(150.00) is a field where I enter 2. In the next div I then display the total. So 150.00 x 2 = 300.00.
I can do this for each item under the section. I then sum the entire items into one global price next to the sections.
Here is a sample of what I'm doing:
$(document).ready(function() {
$(".demolition_num").each(function() {
$(this).keyup(function(){
calculateDemSum();
});
});
});
function calculateDemSum() {
var sum = 0;
$(".demolition_num").each(function(){
if(!isNaN(this.value) && this.value.lenth != 0){
var unitCost = $(".unit_cost1").text();
var _parent = $(this).parent();
var total = _parent.prev().html();
sum += parseFloat(this.value * total);
var subtotal = this.value * total;
$(_parent).next().html(this.value * total);
}
else if (this.value.length !=0){
}
});
$(".cost1").text(sum.toFixed(2));
$("#cost1").val(sum.toFixed(2));
}
You can view all the code here: http://jsfiddle.net/pmetzger/Xeu2T/3/
As you can see in the jquery that right now I have to call each section independently
of the others since I do not want to calculate all of the fields, just the one I'm modifying.
So the question is, can I avoid having to add each sections input type id as the key up to trigger the calculations and make sure the totals get placed correctly?
Note: This code could be duplicated, but the data associated is going to be different. So on the next clients list it might not be Demolition, but Demo and so forth.
Any help will be greatly appreciated.
First of all a couple of pointers:
You don't need to bind events within an each() loop, simply
binding it to a standard selector will bind to all elements that fit
that selector.
You also have multiple <tr> elements with the same id.
You don't need a size attribute on hidden tags
New working fiddle here and the code:
$(document).ready(function()
{
// Bind the event
$("#calc").on("keyup", "input[type='text']", function()
{
calculateSum(this);
});
});
function calculateSum(element)
{
var sum = 0;
var $this = $(element);
var targetClass = $this.attr("class");
// Process each element with the same class
$("." + targetClass).each(function()
{
var thisVal = $(this).val();
// Count invalid entries as 0
if(isNaN(thisVal) || thisVal.length === 0)
{
thisVal = 0;
}
else
{
thisVal = parseFloat(thisVal);
}
// Get the unit cost and calculate sub-total
var unitCost = parseFloat($(this).parent().prev("td.unit_cost").text());
var subTotal = thisVal * unitCost;
sum += subTotal;
$(this).parent().next("td").text(subTotal);
});
var $item = $this.closest("tr").prevAll(".item").first();
$item.find("input.section_cost").val(sum.toFixed(2));
$item.find("td.section_cost").text(sum.toFixed(2));
}
Note that I have modified your HTML slightly - I changed the multiple <tr id="item"> to use classes, I moved where these rows were to better target your subsection totals, I added classes to the subsection totals (both hidden inputs and displayed values), I added a class to your unit value fields and I added an id to the table.
Related
So i have a 'total' field at the bottom of this column.
Above this field are checkboxes, when ticked, the 'total' should update by adding the price of that checkbox, and when unticked, the price should be removed.
So something similar to http://www.tepilo.com/#packages-anc
the below code updates the price when checkbox is clicked
it does nothing when unclicked
when clicked again, it adds to the new current price
$('.col-2 input[type="checkbox"]').on('click', function() {
var attribute_name = $(this).val();
var attribute_price = settings.wsapo_custom[0][attribute_name].price;
var current_price_total = $(".col-2 #update-price").text();
var new_price = parseInt(current_price_total) + parseInt(attribute_price);
console.log(new_price);
$(".col-2 #update-price").text(new_price);
});
thanks in advance
Using the onchange or change function in jquery will suffice here. Check if the checkbox is checked and then just change the data accordingly.
Demo on JSFIDDLE: http://jsfiddle.net/lrojas94/t9d04oeb/
Code:
$('input[type="checkbox"]').change(function(){
var actual = parseInt($('p').text());
if($(this).is(':checked'))
actual+= 100;
else
actual-=100;
$('p').text(actual);
});
And feel free to read the docs about this function: http://api.jquery.com/change/
I have two different IDs. One auto increment (using jquery) from an ID called id="H+currentRow+"(+currentRow+ is the current row). And another that does an ajax request to PHP that appends the form with an id="Z#"(# will be depending on the ID in the database).
Ive done this:
$(document).ready(function(){
$("input").change(function(){
var sum=0;
$("[id^=H]").each(function(){
sum=sum+(+parseInt(this.value));
});
var sum2=0;
$("[id^=Z]").each(function(){
sum2=sum2+(+parseInt(this.value));
});
var total = sum + sum2;
if(isNaN(total)) {
var total = 0;
}
$("#total").text(total);
});
});
But thats not working. It works for the first fields but it work for anything else thats being appended. Anyone know whats going on and why its not working?
when you bind an event direct to an element, new elements appended to page will not trigger the event. you have to bind a parent element where inputs are appended to.
Try this bind:
$('body').on('change', 'input', function () {
// your code remain the same here...
});
you can be more specifc than body, binding the event to parent elements of input.
I want to find all child classes with their id in each mother div that is listed per web page.
With that, the id's of the child div's should be grouped by the mainID - to use with an ajax post.
However, I don't even get the child's id's in jquery 1.11, let alone to group them with the mainID.
This is the code so far:
$(".main-column-name").each(function() {
var mainID = $(this).attr('id');
var subid = $(this).find(".subdiv-name").attr("id");
alert(mainID + ' ' + subid );
});
So, under the mainID should be a group of subID's - if they exist of course.
Any help is welcome!!!
You can write it to an object array and attach the children as a sub-array to this.
var mainEl = $(".main-column-name")
mainArr = [],
childArr = [];
//set the properties in an array to be used later
mainEl.each(function() {
var id = $(this).attr('id')
children = $(this).find('.subdiv-name').attr('id');
children.each(function() {
//add the child IDs to an array
childArr.push($(this).attr('id'))
});
//push all the properties into an array
mainArr.push({ 'name': id, 'children': childArr });
});
//to access the properties, use a loop
$.each(mainArr, function (i, value) {
//get the name
console.log(mainArr[i].name);
//get the children
console.log(mainArr[i].children);
//and to access the child IDs individually, use this loop within the loop
$.each(mainArr[i].children, function(c, id) {
//get the stored value for id
console.log(id)
});
});
Use this carefully though, as running a loop within a loop might cause you some performance issues if there will be lots of children and lots of parents. Someone else might be able to advise on a better way of extracting this information other than this... I will update if I think of a better method myself, but I haven't had too much time to look at it.
I have a shopping cart with a list of items in the cart array. When one is removed, it updates the cart through ajax, however the item number in the array, for each shopping cart item, will not update unless page is refreshed.
<input class="remove_cart_id" type="hidden" value="'.$i.'" />
The $i indicates the number in the array. If an item is removed, this could effect the order of the array, so I want to update $i for each class.
Rather than having to output the entire cart contents, is there an easy way to just update an element for each class. It could be done quite easily, with $i = 0, and i++ for each item in the shopping cart array.
UPDATE:
$('.remove_cart_item').click(function(){
$(this).parent().stop(true, true).fadeOut();
var pid = $('.remove_cart_id', this).val();
$.ajax({
type : 'POST',
url : 'ajax/remove-cart.php',
data : 'pid='+pid,
success : function(data) {
$('#cart_quantity').html(data);
}
});
// update cart array
var i = 0;
$('.remove_cart_id').each(function(){
$(this).val(i);
i++;
};
});
I am using this code now, but there seems to be some sort of bug with the each function, as the code stopped working.
To change values based on the class, try
$(".classname").each(function() {
$(this).val('change');
});
Class generally applies to multiple elements being group together. If you have another element in the same class, the value change will be applied for it as well.
Assuming you need to re-index the values
function reindexCart(){
var count = 0;
$('.remove_cart_id').each(){
$(this).val(count);
count++;
}
}
Or, do you need to decrement the value?
ok, so I have a database comprising of two tables, products and suppliers.
All suppliers fill in a form and their data is then stored in the suppliers table, and the products table contains a list of all of the products, so when the supplier fills in the form, he can choose as many products as he wishes as I use jQuery JSON and AJAX to get the list of all of the products and then populate a drop down list with all of them in it, which can then be cloned as many times as is needed.
The problem I am sitting with now is, how do I insert all of the different products the supplier chooses into the supplier table, or should I rather just relate all of the products he chooses to the one supplier for better normalization since all the products are already there?
I will be using jQuery $.ajax to POST the form data in JSON format to a waiting PHP file, which will then parse it and insert the data into the database.
So basically, I need to figure out how to relate the data in the database to achieve the best normalization possible, and I need to figure out a way of inserting a variable amount of products into the suppliers table or find a way to relate the many products he chooses to the one supplier.
I am very new to relational databases, so any advice on how to proceed would be a great help, so would any other advice you guys may have!
The jQuery code I use to populate clone and POST the products the supplier chooses:
$(document).ready(function() {
var count = 0;
//when clicked it will remove the closest div with a class of 'container'
$("span.remove").live('click', function(){
$(this).closest("div.container").fadeOut(400, function(){
$(this).remove();
$('#button').attr('disabled','');
});
});
//initialize the button
$('#button').attr('disabled','');
$('#button').click(function(){
var count = $("#systems_wrapper > .container").size();
var lastID = $("#systems_wrapper > .container:last").attr('id');
var exploded = lastID.split("_");
var increment = Number(exploded[1])+1;
//if the user has selected 5 products, disable the 'add' button
if(count >= 5){
$('#button').attr('disabled','disabled');
}else {
$('#button').attr('disabled','');
}
//clone the first drop down and give it a different ID, as well as it's child elements
var test = $('#systems_0.container').clone().attr('id', 'system_' + increment).appendTo('#systems_wrapper');
test.children(':nth-child(2)').append('<span class="remove"></span>');
test.children(':nth-child(2)').children(':first').attr('id', 'mail_' + increment).attr('class','dropDowns').attr('onchange','test();');
});
//get the products JSON object returned from test_post.php and run the necessary functions on the returned data
$.getJSON("test_post.php", function(data){
//clean out the select list
$('#box').html('');
//run the loop to populate the drop down list
$.each(data, function(i, products) {
$('#box').append(
$('<option></option>').html(products.products)
);
});
});
});
//this gets all of the products chosen and then gets each ones value and ID, and then posts it to the qwer.php file
function test(){
var sections = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
sections.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
alert(newArray);
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: JSON.stringify(newArray) }
});
}
Thanx in advance!
If i understand the problem correctly from a database level, should you be using an intermediate table called something like ProductSupplier containing a Product_ID and Supplier_ID column.
Then when a supplier selects a product, add both the supplier and product id to a new column in this table.
This will allow multiple suppliers to pick the same product and multiple products to be picked by the same supplier.
EDIT: I meant to say "add both the supplier and product id to a new ROW in this table"