I have this html:
You have almost correct code. The only one bug is that you are storing changed select name in variable id, and then using it in string creation. This should work correctly:
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += '&' + $(this).parent().attr('name') + "="+ $(this).attr('value');
});
$("div").text(str);
});
And simple optimization is always a good practice :)
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
var option = $(this);
str += '&' + option.attr('name') + "="+ option.attr('value');
});
$("div").text(str);
});
You should really catch the values of selected boxes separately based on the ID. I would suggest using two different strings altogether like this:
$("#po").change(function () {
var id = $(this).attr('name');
var str = "";
$("#po option:selected").each(function () {
str += "&"+id+"="+ $(this).attr('value');
});
$("div").text(str);
})
.trigger('change');
$("#garden").change(function () {
var id = $(this).attr('name');
var str2 = "";
$("#garden option:selected").each(function () {
str2 += "&"+id+"="+ $(this).attr('value');
});
$("div").text(str2);
})
.trigger('change');
The way you currently do it, it just assumes that all the selected options are a part of the same select box and concatenates onto the end of the string. If you maintain two seperate strings for the select boxes, you can combine them when it is time to send the URLs by looking at the values of str
and str2
.
You may have to adapt this a little to make sense for your project but the general idea should remain the same.
http://jsfiddle.net/rawsmell/eZKUU/1/
EDIT:
Use this instead:
$("select").change(function () {
//var id = $(this).attr('name');
var str = "";
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += "&"+id+"="+ $(this).attr('value');
});
$("div").text(str);
})
.trigger('change');