Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get this javascript redirect to work in Firefox?

I have got help here to put together this code. And it works perfect in Chrome, Safari and in Internet Explorer. But in Firefox it redirects to a sub-url (probably not right word for it...)

I have the script on a page:

http://example.com/test

enter image description here

And I want to redirect to a new page based on the value the user chooses (and then click the button): So if I choose option #2 I want to get to here: http://example.com/my-test-2

It works in the other browsers, but not in Firefox. In Firefox it in stead redirects to: http://example.com/test?redirect=http%3A%2F%2Fexample.com%2Fmy-test-2 which of course doesn't lead anywhere.

The HTML is loaded in a jquery and Bootstrap environment, and I do use modals on that page. I just mention this in case there is a know error for Firefox using those framworks.

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>

The javascript:

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

Here is a fiddle

Do you see the reason why Firefox behaves like this?

If of interest: I work on a 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

like image 316
Preben Avatar asked May 05 '15 10:05

Preben


People also ask

How do I enable redirects in Firefox?

Options/Preferences -> Advanced -> General : Accessibility : "Warn me when web sites try to redirect or reload the page"

How do I enable cookies and JavaScript on Firefox?

To enable cookies, go to Options > Privacy. If Firefox is set to remember history, cookies are already enabled. To enable JavaScript, go to about:config, search for javascript. enabled, and change it to "true."


1 Answers

You've used preventDefault(), but haven't actually passed the event in to the handler. Also note that using window.location.assign() is better practice. Try this:

$("#mychoice").submit(function(event) { // < 'event' is the parameter passed to the func
    event.preventDefault();
    window.location.assign($('input[name="redirect"]:checked').val());
});
like image 73
Rory McCrossan Avatar answered Nov 15 '22 03:11

Rory McCrossan