Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Apply a class to each of your <code>select#item_list_N</code> and <code>select#size_N</code>. You will get the following HTML:</p> <pre><code>&lt;form&gt; &lt;fieldset&gt; &lt;select id="item_list_0" name="item_list_0" class="item_list"&gt; &lt;option value=''&gt;Select an Item&lt;/option&gt; &lt;/select&gt; &lt;select id="size_0" name="size_0" class="size"&gt; &lt;option value=""&gt;Select Size&lt;/option&gt; &lt;/select&gt; &lt;input id="price_0" name="price_0" size="10" value="Unit Price" /&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;!-- repeated with inputs named: input_name_1 --&gt; &lt;/fieldset&gt; &lt;!-- up to N fieldsets --&gt; &lt;/form&gt; </code></pre> <p>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:</p> <pre><code>$(document).ready(function() { $(".item_list").change(function() { // Let's assume that you only need to retrieve // a unique number to identify the fieldset. var uniquePart = $(this).attr('id').replace(/\D/g, ''); // This part left almost untouched $.getJSON(url, {data}, function(json) { var obj = json.pl.size, options = ['&lt;option value=""&gt;Size&lt;/option&gt;']; for (var i = 0, len = obj.length; i &lt; len; i+= 1) { options.push('&lt;option value="' + i + '"&gt;' + obj[i] + '&lt;/option&gt;'); } // Here we apply the id number $("#size_" + uniquePart).html(options.join('')); }); }); $(".size").change(function() { var $this = $(this), // Same idea here uniquePart = $this.attr('id').replace(/\D/g, ''), size = $this.val(); $.getJSON(url, {data}, function(json) { var price = json.pl.price, // By the way, ID selectors are told // to be more efficient without specifying a tag $("#price_" + uniquePart).val(price[size]); }); }); }); // end ready function </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload