using multiselect dropdown and looping through its values using jquery - php

I have a multiselect drop down, on selecting multiple items from it, i need to pass the value of this multiselect into an ajax file, and create divisions dynamically and load the data retreived from the ajax files into these dynamic divisions.
var itemvalues= [];
$('#MultiSelectItemID :selected').each(function(i, selected) {
itemvalues[i] = $(selected).val();
});
$('#itemContent').html(LoadHTML);
$('#itemDetailsContainer').fadeIn('',function(){
$('#itemContent').load('ajax_calls/item_details.php?ItemID='+$('select[name=MultiSelectItemID]').val() || [],
function(){
$(this).show('highlight');
}); });
Now , i want to loop through each value in the itemvalues[] array and pass it to my php file and get the data and load it into a new division.
Please help.

Will this do the job? (Note I 've changed "MultiSelectItemID" to simply "ItemID" and serialize()d it.)
http://jsfiddle.net/svzsY/8/
var itemvalues = [];
$('#itemContent').html(LoadHTML);
$('#itemDetailsContainer').fadeIn('', function() {
$('#itemContent').load('ajax_calls/item_details.php', ($('select[name=ItemID]').serialize() || []), function() {
$(this).show('highlight');
});
});

Related

How to calculate the sum of ID^ with JQuery

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.

JQuery PHP AJAX filter based on multiple checkbox array

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/

Storing a a lists new order in a suitable way

I'm using jQuery ui's sortable. A list of objects is retrieved from the db an dynamically put into a list, the user drag and drops the list objects and the new order of the list should get saved.
Below is the jQuery code for sortable, which include creating an array of the new list order. However, next step is to do something so that I'm able to use this array in my php code.
The thing is that the user, apart from sorting the list objects also should be able to add some comments and do some other stuff and then submit it all. That is, I'm using a form for this. By that reason I must be able to put in the array with the list order into the form in some way, and here's where I need some help.
What method should I use? Ajax? Local storage? How could this be accomplished?
$('#listElements').sortable({
update: function(event, ui) {
var order = [];
$('.listObject li').each( function(e) {
order.push($(this).attr('id'));
});
}
});
You'll want to use AJAX to send the order array to PHP like so:
$('#listElements').sortable({
update: function (event, ui) {
var order = [];
$('.listObject li').each(function (e) {
order.push($(this).attr('id'));
});
$.ajax({
url: "/save_order_to_db",
type: "post",
data: {
order_data: order
}
}).success(function (data) {
console.log(data);
});
}
});

How can I use the Ajax response in another function

I have a dropdown list with values from the database. I used AJAX to dynamically display the price of the selected item form the database. I want to use the price value for further processing
var dataForFuture;
$.get('ajax/test.html', function(data) {
dataForFuture = data;
// other code...
});

Parsing a JSON object with jQuery and creating two drop down lists with that data

I am trying to dynamically create two drop down lists, one will be provinces, and the other will contain the cities of each province, so when a user chooses a province, the cities drop down will populate, I am using jQuery's $.ajax function to get the data from a database which then passes it back as JSON, here is what I have thus far,
jQuery:
$.getJSON("provinces.php", function(data){
//clean out the select list
$('#province').html('');
//run the loop to populate the province drop down list
$.each(data, function(i, json) {
var province = json.province;
var cities = json.cities;
$('#province').append(
$('<option></option>').html(province)
);
});
});
a snippit of the JSON:
[
{"province":"Eastern Cape","cities":"Mthatha,Njoli,Port Alfred,Port Elizabeth,Queenstown,Uitenhage"},
{"province":"Freestate","cities":"Thaba Nchu,Virginia,Welkom"}
]
I am populating the provinces drop down, but not the cities drop down.
I would like to hear from you guys what you think the best method will be to achieve the cities drop down.
Store the json somewhere, i.e. using $('…').data(key, value).
Add a trigger for the change event on province:
$('#province').live('change', function() {…})
When triggered get the value from province $('#province').val() and use it to get the cities. Loop out the cities as options for the city selector (same technique as you showed above).
Whether the cities select is shown and empty or completely hidden by default is up to you.
(Depending on the number of provinces [amount of data] you could also create all selects in html and simply toggle their display)
Hope this helps!
Copy and go ;)
It fills the province-field like you do... additional there is a map created (province -> citys). The province select field gets an onChange listener. If available, the listener fetchs the cities out of the map and set them into the city-select box.
$(function() {
var data = [
{"province":"Eastern Cape","cities":"Mthatha,Njoli,Port Alfred,Port Elizabeth,Queenstown,Uitenhage"},
{"province":"Freestate","cities":"Thaba Nchu,Virginia,Welkom"}
]
var map = {};
$('#cities').attr('disabled', 'disabled');
$(data).each(function(i, data) {
map[data.province] = data.cities.split(',');
$('#provinces').append('<option value="' + data.province + '">'+data.province+"</option>");
});
$('#provinces').change(function() {
var disable = function() {
$('#cities')
.html('<option>select city</option>')
.attr('disabled', 'disabled');
}
var enable = function() {
$('#cities')
.removeAttr('disabled', 'false')
.html('');
}
if (!$(this).val()) {
disable();
return;
}
else if (typeof map[$(this).val()] == 'undefined') {
alert('invalid city');
disable();
return;
}
enable();
$(map[$(this).val()]).each(function(i, city) {
$('#cities').append(
$('<option></option>')
.text(city)
.val(city)
);
});
});
});

Categories