How to get this javascript redirect to work in Firefox?

I have help to compile this code. And it works great in Chrome, Safari and Internet Explorer. But in Firefox, it redirects to sub-url (perhaps this is not the right word for it ...)

I have a script on the page:

http://example.com/test

enter image description here

And I want to redirect to a new page based on the value that the user selects (and then click the button): Therefore, if I choose option number 2, I want to go here: http://example.com/my-test-2

It works in other browsers , but not in Firefox . In Firefox, it redirects instead: http://example.com/test?redirect=http%3A%2F%2Fexample.com%2Fmy-test-2 which, of course, does not.

HTML is loaded into jquery and Bootstrap, and I use the modals on this page. I just mention this in case there is a bug for Firefox using these frameworks.

Here is the HTML:

I want to choose: <form id="mychoice"> <input type="radio" name="redirect" value="http://example.com/my-test-1"><span>1</span><br> <input type="radio" name="redirect" value="http://example.com/my-test-2"><span>2</span><br> <input type="radio" name="redirect" value="http://example.com/my-test-3"><span>3</span><br> <input type="radio" name="redirect" value="http://example.com/my-test-4"><span>4</span><br> <input type="radio" name="redirect" value="http://example.com/my-test-5"><span>5</span><br /><br /> <input type="submit" value="See result"> </form> 

javascript:

 $(document).ready(function(){ $("#mychoice").submit(function(){ event.preventDefault(); var loc = $('input[name="redirect"]:checked').val(); window.location = loc; return false; }); }); 

Here is the fiddle

Do you see the reason Firefox behaves as follows?

If interested: I'm working on Mac OSX 10.10.2 with Chrome 42.0.2311.90 (64-bit), Firefox 37.0.2, and Windows 8.1 IE 11.09600.17728

+5
source share
2 answers

You used preventDefault() , but did not actually pass event to the handler. Also note that using window.location.assign() is best practice. Try the following:

 $("#mychoice").submit(function(event) { // < 'event' is the parameter passed to the func event.preventDefault(); window.location.assign($('input[name="redirect"]:checked').val()); }); 
+12
source

You have a bug in your JS. Variable event not defined. Try it like this:

 $(document).ready(function(){ $("#mychoice").submit(function(event){ event.preventDefault(); var loc = $('input[name="redirect"]:checked').val(); window.location.href = loc; return false; }); }); 
0
source

All Articles