Olly
Olly

Reputation: 7758

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?

Upvotes: 1

Views: 2301

Answers (2)

kgiannakakis
kgiannakakis

Reputation: 104178

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.

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

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

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

Upvotes: 3

Related Questions