Javascript/jquery for multiple dropdown menus on one page

How can I use the same javascript/jquery for multiple drop down on a single page? Would I select by ID or class?

These are one the same page:

<select id="drop1">
<option value="#">Option 1</option>
<option value="#">Option 2</option>
<option value="#">Option 3</option>

<select id="drop2">
<option value="#">Option 1</option>
<option value="#">Option 2</option>
<option value="#">Option 3</option>

What javascript/jquery should I use to have the page redirect to the correct URL when an option is selected? Functionality should be the same for both dropdowns, but each have unique IDs. I'm not opposed to using the same class for both dropdown (instead of unique IDs) if that method would be easier.


The easiest method would be to use the "onchange" event of the SELECT. You don't need to use jQuery or the "id" attribute.

<select id="drop1" onchange="launch(this)">
    <option value="/drop1opt1.html">Option 1</option>
    <option value="/drop1opt2.html">Option 2</option>
    <option value="/drop1opt3.html">Option 3</option>

<select id="drop2" onchange="launch(this)">
    <option value="/drop2opt1.html">Option 1</option>
    <option value="/drop2opt2.html">Option 2</option>
    <option value="/drop2opt3.html">Option 3</option>

Then create a simple javascript function to change the window's location property.

function launch(opt) {
    window.location = opt.value;

Hope that helps.

If the behavior is both the same then you can either create listeners for the individual IDs, or use the same class and add the listener to that class. To prevent duplicate code, I would suggest the class approach.

<select id="drop1" class="urlRedirect">
  <option selected disabled>--Select--</option>
  <option value="page1">Option 1</option>
  <option value="page2">Option 2</option>
  <option value="page3">Option 3</option>

<select id="drop2" class="urlRedirect">
  <option selected disabled>--Select--</option>
  <option value="page4">Option 1</option>
  <option value="page5">Option 2</option>
  <option value="page6">Option 3</option>

And then the jquery:

 $('select.urlRedirect').change(function() {
  //window.location.href=$(this).val(); to open in same page
    '_blank' // <- This is what makes it open in a new window.

Working jsfiddle:


 ? Change image and text with dropdown
 ? setting id, name from DB to dropdown in angular js
 ? Dropdown Navigation CSS Issue
 ? Custom width and auto height to dropdown in bootstrap
 ? How to make angular dropdown control (not select) in angular form?
 ? jquery count select dropdown which are not disabled and have specific option selected
 ? PHP Dropdown and database
 ? Activate a dropdown option from another button/llink
 ? Php pdo display enum values in dropdown
 ? Keep Bootstrap dropdown open on click