0

I have two dropdowns (which are using Chosen.js). The second dropdown displays custom categories:

<script type="text/javascript">
  jQuery(document).ready(function($) {
    $('select[name="post_type"]').change(function (event) {
        if ($('select[name="post_type"]').val() === 'test') {
            $('select[name="second_dropwdown"]').html("<option>Sorry, no options</option>");
            $('#second_dropwdown').prop('disabled', true).trigger('chosen:updated');
        }else{
            $('#second_dropwdown').prop('disabled', false).trigger('chosen:updated');
        }
    });
  });
</script>

If I choose "test" in the first dropdown, the second dropdown becomes disabled and shows "Sorry, no options". My problem is that when you then choose anything other than "test" afterwards, the second dropdown doesn't populate with the categories again. How would I go about doing that? ie, revert back to the options it had before:

$('#second_dropwdown').prop('disabled', true).trigger('chosen:updated');

Thanks in advance!!

1

You're setting the HTML of the second drop down to essentially blank with:

$('select[name="second_dropwdown"]').html("<option>Sorry, no options</option>");

So when you enable it again, that's the only option. Instead, you might try including that as an actual option within your select and then selecting it when disabling the second drop down. You could either include it in your HTML or add it via JavaScript. Here's an example of the latter.

  jQuery(document).ready(function ($) {
      var $secondDropdown = $('#second_dropdown'), 
          $noOptions;

      // adding the the option with js
      $secondDropdown.append('<option id="no-options">Sorry, no options!</option>');

      // by default, no one needs to see it.
      $noOptions = $('#no-options').hide();

      $('select[name="post_type"]').change(function (event) {
          if ($('select[name="post_type"]').val() === 'test') {
              // Now, select the option and show it
              $noOptions.prop('selected', true).show();
              $secondDropdown.prop('disabled', true).trigger('chosen:updated');
          } else {
              // back in business so let's hide it again.
              $noOptions.hide();
              $secondDropdown.prop('disabled', false).trigger('chosen:updated');
          }
      });
  });

Here's a live example: http://jsfiddle.net/4ngmhmup/

1
  • Your answer worked flawlessly. Thanks so much for your quick and detailed response, I really appreciate it! :) – Guit4eva Aug 31 '15 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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