Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Looks like you're getting tripped up by using the class selectors on your containing <code>div</code> tags.</p> <p>Specifically, the goal of <code>var child</code> is to return an array of <code>option</code> tags. Ideally, you should use the <code>ID</code> attribute the form builder assigns to each element. Not knowing how you opened your form (ie. not knowing the parent model), let's assume your open statement looks something like:</p> <pre><code>&lt;%= form_for @product_batch do |f| %&gt; </code></pre> <p>This will make your <code>product</code> and <code> batch_no</code> select fields look something like:</p> <pre><code>&lt;select name="product_batch[product_id]" id="product_batch_product_id"&gt; &lt;select name="product_batch[batch_no]" id="product_batch_batch_no"&gt; </code></pre> <p>Now, we can refactor your jQuery as follows:</p> <pre><code>jQuery(function() { var child = $('#product_batch_batch_no').html(); $('#product_batch_product_id').live("change", function() { var escaped_parent, parent, options; parent = $('#product_batch_product_id :selected').text(); escaped_parent = parent.replace(/([ #;&amp;,.+*~\':"!^$[\]()=&gt;|\/@])/g, '\\$1'); options = $(child).filter("optgroup[label='" + escaped_parent + "']").html(); $('#product_batch_batch_no').html(options); }); }); </code></pre> <p>The last bit of the your code:</p> <pre><code>if (options) { jQuery('.batch').html(options); return jQuery('.batch').parent().show(); } else { jQuery('.batch').empty(); } </code></pre> <p>is literally destructive. When a product does not have a <code>batch_nojQuery('.batch').empty();</code> removes the html inside: </p> <pre><code>&lt;div class="batch"&gt;&lt;/div&gt; </code></pre> <p>Once removed, this code is gone...which is probably not what you want.</p> <p>Anyway, I agree with Ryan Bates' opinion that this is a great, unobtrusive way to implement dynamic select boxes. You may want to checkout the revised RailsCast at <a href="http://railscasts.com/episodes/88-dynamic-select-menus-revised" rel="nofollow">http://railscasts.com/episodes/88-dynamic-select-menus-revised</a></p> <p>Best of luck!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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