I’m pretty new to JQuery, and this is probably not the best use case to learn on, but it’s the project I have to do.
Basically I have a form, with a set of inputs where the values of the child inputs will be changed based on the values in the parent. (Using Ajax to retrieve the data sets).
Essentially:
Item List -> Available Sizes -> display Price for selected size
This is all pretty much straight forward, and I have something functioning for a single set of grouped inputs.
But I’m stuck on how to make this work for ‘N’ instances. I’m using an index on the element ids to group the related elements (i.e. input_name_[0 .. N]) and give unique ids throughout the document.
The HTML:
<form ...>
<fieldset>
<select id="item_list_0" name="item_list_0">
<option value=''>Select an Item</option>
</select>
<select id="size_0" name="size_0">
<option value="">Select Size</option>
</select>
<input id="price_0" name="price_0" size="10" value="Unit Price" />
</fieldset>
<fieldset>
..... repeated with inputs named: input_name_1
</fieldset>
.
. <!-- up to N --> fieldsets -->
.
</form>
JQuery script that works for a specific id “set” (i.e.: item_list_0)
<script type="text/javascript" src="/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select#item_list_0").change(function(){
$.getJSON(url,{data},
function(json){
var obj = json.pl.size;
var options = '<option value="">Size</option>';
for (var i = 0; i < obj.length; i++) {
options += '<option value="' + i + '">' + obj[i] + '</option>';
}
$("select#size_0").html(options);
});
});
$("select#size_0").change(function(){
$.getJSON(url,{data},
function(json){
var price = json.pl.price;
var size = $("select#size_0").val();
$("input#price_0").val(price[size]);
});
});
}); // end ready function
</script>
For reference the json returned from the url is:
{"pl":{"name":"item Name","price":["110.00","40.00","95.00"],"size":["LG","SM","MED"]}}
My challenges:
1. Need to remove the specific ID in the .click events to be dynamic for all ‘N’ of the field sets
2. Need to keep the relationships for the chains. (item_list_0.click should NOT effect size_1 option list)
I have looked at the jquery.selectChain plugin, and the jquery.cascade plugin, but neither seems to work for my particular situation.
Apply a class to each of your
select#item_list_Nandselect#size_N. You will get the following HTML:Then you could use a generic function to serve every single instance of your fieldset. The following is a raw draft of what I mean: