0

I need to make a conditional select statement that displays a set of values IF and only IF a choice is made from another select statement that is not = 0. I tried a bunch of a basic Javacripts that use display:none, but can't seem to find the right combination to make it cross compatible between all browsers. Do I need to use jQuery? Unfortunately, I only have some basic Javascript skills, so I may have missed something basic.

<h2>Station</h2>

<label for="station"></label>
<select name="station" id="station">
  <option value="0">None</option>
  <option value="1">Fire Station 1</option>
  <option value="2">Fire Station 2</option>
  <option value="3">Fire Station 3</option>
  <option value="4">Fire Station 4</option>
  <option value="5">Fire Station 5</option>
  <option value="6">Fire Station 6</option>
  <option value="7">Fire Station 7</option>
  <option value="8">Fire Station 8</option>
  <option value="9">Fire Station 9</option>
</select>

<br clear="all" />

<h2>Categories</h2>
<select name="category" id="category" style="width:160px;">
  <option value="">Choose One</option>

  <option value="11">Company Operations Alert</option>

  <option value="20">**Apparatus Issue</option>

  <option value="18">**Equipment Notice</option>

  <option value="19">**Station Announcement</option>

  <option value="21">**Station Maintainence</option>

</select>
SiriusPhil
  • 149
  • 1
  • 9
  • So what you want is to display the options in the second select based on the options in the first select? – Terry Oct 15 '14 at 14:49
  • Hiding options can't be done in a (technically valid) cross-browser way. There are some workarounds (e.g. http://stackoverflow.com/questions/9234830/how-to-hide-a-option-in-a-select-menu-with-css) but I'd hesitate to trust them in future browsers. Better to keep a list of options in a JS array somewhere, and add them to the `select` when the conditions are right. – Paul Roub Oct 15 '14 at 14:50

1 Answers1

0

Yes, using jQuery, your js will be like:

$('#station').on('change', function() {
    var seln = $(this).val();
    if (seln != 0) {
        $('#category').show();
    } else {
        $('#category').hide();
    }
});

If you want an ajax request to load the second Category select box:

$('#station').on('change', function() {
    var seln = $(this).val();
    if (seln != 0) {
        $.ajax({
            url: "ajax_url.php",
            type: "GET",
            data: "station=" + seln
        }).done(function(a) {
            $('#category').html(a).show();
        });
        $('#category').show();
    } else {
        $('#category').hide();
    }
});

You'll have to make some changes to the above code as per your exact requirements.

Ananth
  • 4,227
  • 2
  • 20
  • 26