Page does not redirect when setting window.location in JavaScript

User007 picture User007 · Jul 16, 2013 · Viewed 11.7k times · Source

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?

Answer

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();"