Add link to select option when clicked

Hi there,

I have a select dropdown which I am adding some new options to via jQuery. What I would like to do is to send the user to a URL when the select option is clicked.

I’ve managed to add the options, but can’t work out how to make the link go to the URL in the value.

$('select[name="ap"]').append($('<option>', {value:'http://www.google.com', text:'Google'}));    
$('select[name="ap"]').append($('<option>', {value:'http://www.google.co.uk', text:'Google UK'}));    
$('select[name="ap"]').append($('<option>', {value:'http://www.google.fr', text:'Google FR'}));    

Any ideas how I can do this?

Thanks

Like this:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Select onChange</title>
  </head>

  <body>
    <select name="ap">
      <option>Please choose an option</option>
    </select>

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script>
      const $select = $('select[name="ap"]');
      const opts = [
        {'value':'http://www.google.com', 'text':'Google'},
        {'value':'http://www.google.co.uk', 'text':'Google UK'},
        {'value':'http://www.google.fr', 'text':'Google FR'}
      ];

      opts.forEach(function(obj){
        $("<option />", {
          value: obj.value,
          text: obj.text
        }).appendTo($select)
      });

      $select.on("change", function(){
        window.location = this.value;
      });
    </script>
  </body>
</html>

Also, maybe consider tidying up the code that appends the elements to the select?

Many thanks :slight_smile: It workled

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