0

I have the following script that will display the State select drop-down if the Country United States is selected.

<script type="text/javascript">

    $(function() {
        $('#country').change(function(){
            $('.state').hide();
            $('#' + $(this).val()).show();
        });
    });

</script>

<div class="large-6 columns">
   <div class="input-wrapper">
      <label>
         Country
         <select name="user_country" id="country">
            <option selected disabled value=''>Select Country</option>
            <option value="USA" <?php if ($_POST['user_country']=="USA") echo "selected"; ?>>United States</option>
            <option value="United Kingdom" <?php if ($_POST['user_country']=="United Kingdom") echo "selected"; ?>>United Kingdom</option>
            <option value="Ireland" <?php if ($_POST['user_country']=="Ireland") echo "selected"; ?>>Ireland</option>
         </select>
      </label>
   </div>
</div>
</div>
<div id="USA" class="state" style="display:none">
   <div class="row">
      <div class="large-6 columns">
         <div class="input-wrapper">
            <label>
               State
               <select name="user_state">
                  <option selected disabled  value=''>Select State</option>
                  <option value="AL" <?php if ($_POST['user_state']=="AL") echo "selected"; ?>>Alabama</option>
                  <option value="AK" <?php if ($_POST['user_state']=="AK") echo "selected"; ?>>Alaska</option>
                  <option value="AZ" <?php if ($_POST['user_state']=="AZ") echo "selected"; ?>>Arizona</option>
               </select>
            </label>
         </div>
      </div>
   </div>
</div>

That all works fine but I am trying to get the script to run on page load if the United States is already selected.

Any ideas how to achieve this?

Many thanks,

John

1 Answer 1

4

You have to trigger it explicitly:

$(function() {
    $('#country').change(function(){
        $('.state').hide();
        $('#' + $(this).val()).show();
    }).trigger('change'); // <----- trigger the event here || or .change();
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.