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

asked Jul 21, 2016 at 12:02

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();
});
answered Jul 21, 2016 at 12:03
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.