views:

165

answers:

2

Hi Guys,

I have some onchange events setup in jQuery which are used to populate a select dropdown boxbased on what is selected in another select dropdown.

I need these to also run on page load that so that results are returned based on what the first select box is at on page load (otherwise i endup with an empty select box). Ive had a look around the internets but cant find anything that fits exactly what i want to do

My Jquery code is

        $(function(){


    //Get Contacts for Company

      $("select#ContactCompanyId").change(function(){
        var url = "contactList/" + $(this).val() + "";
        $.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
          var options = '';
          $.each(j, function(key, value){
        options += '<option value="' + key + '">' + value + '</option>';
          })
          $("select#QuoteContactId").html(options);
        })
      })

    //Get list of product Categories

      $("select#ProductCategory").live('change', function(){
        var url = "productList/" + $(this).val() + "";
        var id = $(this).attr('name');
        $.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
          var options = '';
        options += '<option value="0">None</option>';
          $.each(j, function(key, value){
        options += '<option value="' + key + '">' + value + '</option>';
          })
          $("select#QuoteItem" + id + "product_id").html(options);
        })
      })

    //Function to add product data into the form

      $(".Product").live('change', function(){
        var url = "productData/" + $(this).val() + "";
        var id = $(this).attr('title');
        $.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
        $("#QuoteItem" + id + "name").val(j['Product']['name']);
        $("#QuoteItem" + id + "price").val(j['Product']['price']);
        $("#QuoteItem" + id + "description").val(j['Product']['description']);
        })
      })
    })

Thanks in advance for your help

A: 
$(document).ready(function() {  
    $('#your_select_id').change();
});

This fires the change event for your select, with its current value. Its the equivlent of a user selecting the current value, and it will fire any events attached to it that would fire from an onchange event.

Erik
+2  A: 

You can just trigger the event just after binding it with .trigger() like this:

$("select#ContactCompanyId").change(function(){
    var url = "contactList/" + $(this).val() + "";
    $.getJSON(url,{id: $(this).val(), ajax: 'true'}, function(j){
      var options = '';
      $.each(j, function(key, value){
    options += '<option value="' + key + '">' + value + '</option>';
      })
      $("select#QuoteContactId").html(options);
    });
  }).trigger('change');
Nick Craver