开发者

Selecting a value from the select box when options added by an ajax call

开发者 https://www.devze.com 2022-12-19 16:30 出处:网络
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 i

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

  <%= builder.hidden_field :ingredient_id %></div>

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.

I have an issue when I open an existing recipe in edit mode...

I have the following html

<%= builder.hidden_field :ingredient_id %>
<%= builder.select(:serving_size_id, '') %>

jQuery code

jQuery.fn.bindServingSizes = function(ingredientid) {
    var $this = $(this);

    $.getJSON("/serving_sizes?ingredientid=" + ingredientid, function(j) {

        var options = "<option value=''>Please select a serving size</option>";
    for (var i=0; i < j.length; i++)
      options += '<option value="' + j[i].serving_size.id + '">' + j[i].serving_size.name + '</option>';

        $this.html(optio开发者_StackOverflowns);
    });
  };

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. My question: How will I select the correct option in the select box? I have the data in the column "serving_size_id", but I don't know how to get it's value so I can set the correct selected item by value.

I hope I am clear enough in my explanation.


I am no jQuery expert at all, but by the looks of your example I see that you just create HTML to supply the available options.

Therefore you can add the selected="selected" attribute to the option which corresponds with the value of serving_size_id. Getting the the value from serving_size_id using jQuery can be done using:

var serving_size = $("#serving_size_id").val();

This value van be used in your for loop to 'find' the selected option.


Using jQuery, you can set the selected <option> by:

$(combo).val('selectedValue'); // *

Documentation: http://api.jquery.com/val/#val2

*your code didn't allow me to use real names and values on the sample code

0

精彩评论

暂无评论...
验证码 换一张
取 消