3

I am trying to redirect the page dynamically depending upon the value of the dropdown box. I get the value of drop down box in JavaScript. Depending on the dropdown value I want to redirect the page.

This is sample code:

<script type="text/javascript">
        function RedirectMe(){
            var chosanDept = document.getElementById("Dept");
            var str = chosanDept.options[chosanDept.selectedIndex].text;
            if(str=='HR')
                { 
                    alert('Yes in IF' + str);
                    window.location = "http://www.google.com";
                }
        }
    </script>

here chosanDept is the variable to get the value of dropdown box. But I am not able to redirect page using various function like window.location, location.replace, location.href. And one more my if condition works, I get the alert 'Yes in IF HR'

What goes wrong here?

5
  • Do you get any errors in the console? (F12 in Chrome or IE, Ctrl+Shift+K in Firefox.) Commented Jul 16, 2013 at 8:12
  • @RichieHindle, i didn't get any errors in console in both the browser Commented Jul 16, 2013 at 8:19
  • Hi Optimus, your code works if you use onChange event on the select element like <select id="Dept" onChange="RedirectMe()"> <option>select</option> <option>HR</option> </select> Commented Jul 16, 2013 at 8:28
  • @RupamDatta Actually i am submitting the form. So i have added event in the form only as '"onSubmit = "RedirectMe()"'. And all the including select are inside the form only. Commented Jul 16, 2013 at 8:33
  • Okay. I tried your code and it worked like a gem. Anyways, great work. Commented Jul 16, 2013 at 8:37

1 Answer 1

9

Try adding return false; to the end of your RedirectMe() function

And then wherever you are calling the function, make sure you put return there, like onclick="return RedirectMe();"

Sign up to request clarification or add additional context in comments.

4 Comments

thanks a lot, adding return false and return RedirectMe() works fine. But i am not getting how it works by adding return?. Because in the standalone application just for redirecting, it works without the return statement.
@Optimus I believe it is because returning false cancels the submission of your form, which is what you want to do, stop submitting your form and go somewhere else.
yes, it doesn't submit the form with the return. So is there any other way to achieve this. Form submission and the redirection in the same.
@Optimus Not as far a I know, I guess if you want to process the form submission and then redirect, you should do the redirect server side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.