0

I have this <select> that when a user selects an option in there, performs an AJAX to the backend then show/hide additional <select>:

$('#select1').on('change', function() {
    // Get fruit information
    $.ajax({
      type: 'POST',
      url: '/path/to/ajax',
      data: {id: $(this).val()},
      dataType: 'json',
      success: function (data) {
        if (data.type == "apple") {
          $('#select2').addClass('hide');
          $('#select3').addClass('hide');
        }
        else if (data.type == "banana") {
          $('#select2').removeClass('hide');
          $('#select3').removeClass('hide');
        }
      }
    });
});

This works fine. When I submit the form the backend performs a validation then if it fails it loads the page again, however, the #select1 has the value I chosen earlier but the other <select> that suppossed to show is hidden. Is it possible to trigger $('#select1').on('change', function() when the page loads?

Leandro Garcia
  • 3,138
  • 11
  • 32
  • 44
  • You want to trigger with ajax or the whole page reload? – Bilal Jan 30 '14 at 05:36
  • @Bilal - I guess that would be the whole page reload. – Leandro Garcia Jan 30 '14 at 05:38
  • These links may help `http://stackoverflow.com/questions/4247264/how-to-trigger-jquery-change-event-in-code` and `http://api.jquery.com/trigger/` . `$('#select1').trigger("change");` on page load. Not tested – zamil Jan 30 '14 at 05:39
  • @zamil - That is what first came to my mind, and I already did that but nothing happens. – Leandro Garcia Jan 30 '14 at 05:41
  • You can pass a php variable as a flag indicating this select should be hidden or not and apply class hide if the flag is true. ` – Bilal Jan 30 '14 at 05:42
  • 1
    `trigger()` should work fine here. Where did you place `$('#select1').trigger("change");`? Is it before or after the `$('#select1').on()` event handler? I suggest you place it after the `on()` event. – missing_one Jan 30 '14 at 05:58

1 Answers1

0

Checkout the .trigger() of jquery

here is a simple demo to do so

Fiddle

Saurabh
  • 1,007
  • 2
  • 10
  • 24