Set default view when toggling divs by class with jQuery

I have a dropdown list that is dynamicly generated from a database table, when a value is selected the divs below the dropdown are filtered - if a data attribute matches the chosen value they are shown, if it does not they are removed - the first option of the list I want to say ‘Select your location…’ and therefore has no matching value assigned to it.

On first load (before a selection is made) all divs are shown with no filter applied.

How can I set a default view so that if a user takes it back too select your location or wishes to revert to all results again there isn’t just a blank page shown?

The code I’m using is:

<select id="town-select" class="soflow">
        <option>Select your location...</option>
        <?php foreach(get_alllocations() as $locationlist): ?>
          <option value="<?php echo htmlentities($locationlist['city'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlentities($locationlist['city'], ENT_QUOTES, 'UTF-8'); ?></option>
        <?php endforeach; ?> 

    <script type="text/javascript">
         $("div[data-town=" + this.value +"]").show();

Hi Ben,

Within the change handler, you could check if the current value is ‘all’ (or whatever you want to set your ‘Select your location…’ option to) and show all the divs, eg:

  if (this.value === 'all') {
  } else {
    $("div[data-town=" + this.value +"]").show();
1 Like

Perfect! Works like a charm - exactly what I was after. Thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.