Note that there are some explanatory texts on larger screens.

plurals
  1. POSelecting a value from the select box when options added by an ajax call
    primarykey
    data
    text
    <p>I have a form to add recipes, in the same form the user can add multiple recipe ingredients. Every ingredient the user adds is done by an ajax call, this way I don't have to display a select box of ingredients. When the user user select's an ingredient the id of the selected ingredient is stored in a hidden input</p> <pre><code> &lt;%= builder.hidden_field :ingredient_id %&gt;&lt;/div&gt; </code></pre> <p>When the user selects an ingredient from the list, a trigger an ajax call to populate another select box which display's all the serving sizes based on the ingredient. This set up works perfectly when I am adding new recipes. </p> <p>I have an issue when I open an existing recipe in edit mode...</p> <p>I have the following html</p> <pre><code>&lt;%= builder.hidden_field :ingredient_id %&gt; &lt;%= builder.select(:serving_size_id, '') %&gt; </code></pre> <p>jQuery code</p> <pre><code>jQuery.fn.bindServingSizes = function(ingredientid) { var $this = $(this); $.getJSON("/serving_sizes?ingredientid=" + ingredientid, function(j) { var options = "&lt;option value=''&gt;Please select a serving size&lt;/option&gt;"; for (var i=0; i &lt; j.length; i++) options += '&lt;option value="' + j[i].serving_size.id + '"&gt;' + j[i].serving_size.name + '&lt;/option&gt;'; $this.html(options); }); }; </code></pre> <p>I have an ajax call which runs when the page loads, it reads the value in the hidden input and gets the serving sizes and adds it as options to the select box. <strong>My question</strong>: How will I select the correct option in the select box? I have the data in the column "serving_size_id", <strong>but I don't know how to get it's value so I can set the correct selected item by value.</strong></p> <p>I hope I am clear enough in my explanation.</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.
 

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