开发者

Populating a SELECT element using AJAX on page load and on change

I have a SELECT element in a form which I'm populating using AJAX when the select option changes. This works really well using the 开发者_高级运维following code:

$(function() {
  function populate() {
    $.getJSON('/action/' + $(this).val(), {}, function(data, textStatus) {
      var el = $('select#two');
      el.html('');  // empty the select
      $.each(data, function(idx, jsonData) {
        el.append($('<option></option>').val(jsonData.id).html(jsonData.name));
      });
    });
  }

  $("select#one").change(populate);
});

Of course this only works when the first drop down is first changed. What I'd like to do is use the same method to pre-populate the second drop down when the page firsts loads.

The only way I can think of is to modify the getJSON call as follows:

$.getJSON('/action/' + $("select#one").val(), {}, function(data, textStatus) 

(i.e. don't use $(this))

and then simply calling this at the bottom of the 'on load' initialiser block:

populate();

Whilst this works, it just doesn't feel right. Can anyone suggest a better solution?


You can trigger the change event by adding .trigger('change') to your selector like so:

$("select#one").change(populate).trigger('change');


In my opinion it is better to populate the first select using server-side code. Doing it with an Ajax call may introduce an interval, where the page appears but the select box remains empty. This can easily happen when the page comes from the cache. The user will get confused and may need to try once more to see the selections appearing.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜