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?
Related
I am using Jquery-option-tree plugin on a standalone website not based on Wordpress as in example 7 on the demo page, except that I am not passing a .txt file but a PHP page is generating the array of < options > to be passed to the plugin.
http://kotowicz.net/jquery-option-tree/demo/demo.html
This perfectly works: so let's say that the user wants to select a category for a new product, the plugin suits the purpose generating a nice: " Food -> fruit -> apples " upon user clicks. (see demo page ex. 7)
What instead if a product already exists with its categories assigned? I want to show it to the user when he edit that product, preloading the tree.
I have the ids path coming from database, so it would just be a matter of having the plugin to run without the user interact, using the value I pass. I saw this question: jQuery simulate click event on select option
and tried to simulate user' click with this (and other) methods with no luck.
$('#select')
.val(value)
.trigger('click');
Here the call to the function:
$(function() {
var options = {
empty_value: '',
set_value_on: 'each',
indexed: true, // the data in tree is indexed by values (ids), not by labels
on_each_change: '/js/jquery-option-tree/get-subtree.php', // this file will be called with 'id' parameter, JSON data must be returned
choose: function(level) {
return 'Choose level ' + level;
},
loading_image: '/js/jquery-option-tree/ajax-load.gif',
show_multiple: 10, // if true - will set the size to show all options
choose: ''
};
$.getJSON('/js/jquery-option-tree/get-subtree.php', function(tree) { // initialize the tree by loading the file first
$('input[name=parent_category_id]').optionTree(tree, options);
});
});
Here you can see the plugin:
https://code.google.com/p/jquery-option-tree/
I don't know that plugin, but looking at the examples there seems to be one that fits your need; Example 6 - AJAX lazy loading & setting value on each level change.
This would, in theory, just require some config options:
preselect: {'demo6': ['220','226']}, // array of default values - if on any level option value will be in this list, it will be selected
preselect_only_once: true, // prevent auto selecting whole branch when user maniputales one of branch levels
get_parent_value_if_empty: true,
attr: "id" // we'll use input id instead of name
If this doesn't fit you need though, you could initiate it from an event, like change, keyup, etc.
$(document).on('change', '#select', function() {
$('#nextSelect').val($(this).val());
})
$(document).on('change', '#nextSelect', function() {
$('#finalInput').val($(this).val());
})
Yes, you are right Mackan ! I saw that "preselect" option but I was initially unable to use it transferring the path from database to javascript, I ended up with my "newbie" solution to match the syntax:
preselect: {'parent_category_id': [0,'2','22']},
PHP
$category_path comes from DB query and is like "0,2,76,140,"
$path = explode(',', $category_path);
$preselect="";
foreach ($path as $value) {
$int = (int)$value;
if ($int != 0) $preselect.= "'". $int ."',";
else $preselect.= $int.","; // have to do this as ZERO in my case has to be without apostrophes ''
}
$preselect = "{'parent_category_id':[".$preselect."]}"
JS
var presel= <?php echo($preselect); ?>;
var options = {
preselect: (presel),
}
Any suggestion for a better code ?
Thanks a lot !!
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.
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.
I'm hoping someone can point me in the right direction. I'm primarily a PHP developer but I'm really trying to get my head around jquery and javascript more due to the increasing number of AJAX work requests we receive.
Basically I have a sidebar filter that works fine. It is based on 3 things. A group, category and sub category. So for example, Boots as the category, Leather (type) as a sub category and Black (colour) as tertiary filter. At the moment it works based on a GET form. However I want to use live filters instead so as they click a checkbox, it updates the results based on a query. I can write all the PHP for this but I'm struggling to get the data together by jQuery. I've looked at using jQuery .each and .change.
There are 3 groups of checkboxes and they are all based on arrays. So for example again: category[], subcategory[], tertiary[].
Thanks in advance for the help.
Some example HTML
<input id="$ProdCatLabel" class="side_filter_checkbox" name="ProdCatFil[]" type="checkbox" value="$ProdCat">
<input id="$ProdSubCatLabel" class="side_filter_checkbox" name="ProdSubCatFil[]" type="checkbox" value="$ProdSubCat">
<input id="$BrandingLabel" class="side_filter_checkbox" name="BrandFil[]" type="checkbox" value="$Branding">
My attempts:
var prodcats = $('side_filter_prodcats[name="ProdCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
var prodsubcats = $('side_filter_prodsubcats[name="ProdSubCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "[ENTER PHP URL HERE]",
data: "ProdCats=" + prodcats + "ProdSubCats=" + prodsubcats,
success: function(msg) { $(".content_area").html(msg); }
});
Am I barking up the right tree here?
Ok let's say your checkboxes have the classes category, subcategory and tertiary. You could attach a click event handler to each group that calls the function to load in the correct data, passing the checkbox value and a class or data-attribute to the function as parameters.
// Your main DOM ready function
$(document).ready(function() {
// Checkboxes click function
$('input[type="checkbox"]').on('click',function(){
// Here we check which boxes in the same group have been selected
// Get the current group from the class
var group = $(this).attr("class");
var checked = [];
// Loop through the checked checkboxes in the same group
// and add their values to an array
$('input[type="checkbox"].' + group + ':checked').each(function(){
checked.push($(this).val());
});
refreshData(checked, group);
});
function refreshData($values, $group){
// Your $values variable is the array of checkbox values
// ie. "boot", "shoe" etc
// Your $group variable is the checkbox group
// ie. "category" or "subcategory" etc.
// Now we can perform an ajax call to post these variable to your php
// script and display the returned data
$.post("/path/to/data.php", { cats: $values, type: $group }, function(data){
// Maybe output the returned data to a div
$('div#result').html(data);
});
}
});
Here's an example of the checkbox click function in action: http://jsfiddle.net/F29Mv/1/