Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display image array based on selection

I am trying to accomplish the following....

  1. Create a dropdown menu that is a list of last names
  2. When a last name is selected, display all of the images with that last name

Attempt...

<script>
    function displayAllImages() {
        var smith = ["text instead of Smith pictures","text instead of Smith pictures2"];
        var jones = ["text instead of Jones pictures"];

        for (i=0;i<2;i++) {
          document.write("<li><p>" + smith[i] + "<p/></li>");
        }
    };
</script>
<select>
  <option value="smith">Smith</option>
  <option value="jones">Jones</option>
</select> 
<div>
    <ul>
        <script>displayAllImages();</script>
    </ul>
</div>

What I need help with is relaying the dropdown selection to the the javascript function so I can switch between arrays.

Thank you!

like image 288
nickruggiero Avatar asked Dec 07 '25 00:12

nickruggiero


1 Answers

Use on change event to capture the changes in you select and append the lis items to the target ul using the related array to the selected value.

NOTE : Using window[string] in the example bellow to get the variable name from string (selected option value).


var smith = ["text instead of Smith pictures","text instead of Smith pictures2"];
var jones = ["text instead of Jones pictures"];

$('select').on('change', function(){
    $('ul').empty(); //reset ul
  
    var selected_array = window[$(this).val()];

    for (i=0;i<selected_array.length;i++) {
      $('ul').append("<li><p>" + selected_array[i] + "<p/></li>");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="smith">Smith</option>
  <option value="jones">Jones</option>
</select> 
<div>
  <ul></ul>
</div>
like image 191
Zakaria Acharki Avatar answered Dec 09 '25 14:12

Zakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!