Aquatwit
Aquatwit

Reputation: 3

js hide function

When the page is loaded (the first dropdown (div StatusID) is dynamically populated from the mysql db) or the user selects Unemployed - EI from the first dropdown box, the div status_sub_6 shows the second select statement.

My .hide .show function activates fine on change but the function hides the second dropdown list on the loading of the page even if the dynamically populated values of the first select (StatusID) meet the compare criteria.

I'm sure that I need an onload function which overrides the following .js code but would really appreciate a bit of help in composing the additional code.

JavaScript:

$(document).ready(function(){
    $('#status_sub_6').hide();

     $('#StatusID').change(function () {
        if ($('#StatusID option:selected').text() == "Unemployed - EI"){
            $('#status_sub_6').show();
        }
         else { 
              $('#status_sub_6').hide();
         }
    });
});

Upvotes: 0

Views: 243

Answers (3)

spadelives
spadelives

Reputation: 1628

You could also do this:

$(document).ready(function(){
    if ($('#StatusID option:selected').text() == "Unemployed - EI"){
        $('#status_sub_6').hide();
    }

     $('#StatusID').change(function () {
        if ($('#StatusID option:selected').text() == "Unemployed - EI"){
            $('#status_sub_6').show();
        }
         else { 
              $('#status_sub_6').hide();
         }
    });
});

or a bit more elegant solutions:

$(document).ready(function () {
    toggleSub();

    $('#StatusID').change(function () {
        toggleSub();
    });
});

function toggleSub() {
    if ($('#StatusID option:selected').text() == "Unemployed - EI") {
        $('#status_sub_6').hide();
    }
    else {
        $('#status_sub_6').show();
    }
}

Upvotes: 0

GGio
GGio

Reputation: 7653

try:

$(function() {
   $('#status_sub_6').hide();
   $(document).on('change', '#StatusID', function () {
      if ($('#StatusID option:selected').text() == "Unemployed - EI"){
        $('#status_sub_6').show();
      }
      else { 
        $('#status_sub_6').hide();
      }
   });

   $('#StatusID').change();
});

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

You can do this by triggering a change event right after load.

$(document).ready(function(){
    ...
    // your current code
    ...
    $('#StatusID').trigger('change'); // trigger a change
});

Upvotes: 1

Related Questions