Rik Telner
Rik Telner

Reputation: 279

Redirect after option has been chosen

I have this script, that gives me possiblity of menu for user.

How to make user being redirect to specific page after specific choice has been made?

<form action="...">
    <select name="name">
        <option>Option 1</option>
        <option>Option 2</option>
    </select>
</form>

Option 1 = option1.php
Option 2 = option2.php

Upvotes: 0

Views: 534

Answers (2)

Dory Zidon
Dory Zidon

Reputation: 10719

You can use the onchange event of the select:

Step 1:

<script>
  function redirectChange() {
      var newUrl = this.options[this.selectedIndex].value;
      document.location.href = "http://www.yourbaseurl.com/" + newUrl;
  }

</script>

Step 2 - Option 1: After the function hook up the event using addEventListener (I prefer this way as it allows chaining - notice you must add an html id to the select)

<script>
document.getElementById("<insert your select id").addEventListener("change",redirectChange,false);  
</script>

Step2 - Option 2: Or change the html with direct onchange event hooking (I prefer the previous)

<form action="...">
    <select name="name" onchange="redirectChange(this)>
        <option value="option1.php">Option 1</option>
        <option value="option2.php">Option 2</option>
    </select>
</form>

Working jsFiddle:

http://jsfiddle.net/mapVz/1/

Upvotes: 1

itz2k13
itz2k13

Reputation: 159

Do you want to redirect on select of option itself, or on submit of form, In former case, you need it in jquery (client side) and in the latter, you can do it in server side on form submit.

For Client Side:

jQuery("#select_id").on('change', function(){
   var urlPath = jQuery(this).val().data('url');
   window.location.href = "http://www.projecturl.com/"+urlPath;
});

given the select id looks as below,

<select id="select_id">
   <option data-url="option1.php">Option 1</option>
   <option data-url="option2.php">Option 2</option>
</select>

For Server Side:

You need to write the redirection logic in the form submission action depending on param you receive.

Upvotes: 1

Related Questions