Browser redirection based on switch value

Is there an easier way to redirect the browser based on the selection with a switch? It works, but from what I read on the World Wide Web, there may be an easier way.

This is my form:

<form>
<input type="radio" name="value" value="google"><span>Google</span><br>
<input type="radio" name="value" value="yahoo"><span>Yahoo</span><br>
<input type="radio" name="value" value="bing"><span>Bing</span>

This is my jquery:

$(function() {
$("input[name$='value']").click(function() {
    var value = $(this).val();
    if (value == 'google') {
        window.location.assign("http://www.google.com");
    }
    else if (value == 'yahoo') {
        window.location.assign("http://www.yahoo.com");
    }
    else if (value == 'bing') {
        window.location.assign("http://www.bing.com");
    }
});});

Thanks in advance

+5
source share
4 answers

I would change html a bit to something like this:

<form>
<input type="radio" name="redirect" value="http://google.com"><span>Google</span><br>
<input type="radio" name="redirect" value="http://yahoo.com"><span>Yahoo</span><br>
<input type="radio" name="redirect" value="http://bing.com"><span>Bing</span>
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$('input[type="radio"]').on('click', function() {
     window.location = $(this).val();
});
</script>

I would also switch to the .on () method, since it just makes a .on () call anyway. The reason is that .click () simply makes a call to the .on () method, creating one additional function call that is not really needed. Plus .on () is much more flexible!

+4
source

LIVE DEMO

$(function() {

    $("input[name$='value']").change(function() {
        window.location.assign("http://www."+ this.value +".com");
    });

});
+1
source

window.location.replaceis the way to go if you need http redirection. However, if you want to save the history (the current back button of the browser), it will be best for you to choose one of window.locationor window.location.href. If this is a one-page application, you can also consider window.location.hashfor hashed URL changes.

To get the value of the switch, you can try

$('input[type=radio]').on('change', function(e) {
   // preferred window location change appropriate as mentioned above
});

For jquery based solution:

$('input[type=\'radio\']').on('change', function(e) {
   $(location).attr('href', this.value);
});
0
source

I would set url as the value of the switch.

<form>
<input type="radio" name="websiteRadio" value="http://www.google.com"><span>Google</span><br>
<input type="radio" name="websiteRadio" value="http://www.yahoo.com"><span>Yahoo</span><br>
<input type="radio" name="websiteRadio" value="http://www.bing.com"><span>Bing</span>
</form>

$(document).ready(function()
 $("input[name='websiteRadio']").click(function() {        
    window.location = $(this).attr('value');
 });
});
-1
source

All Articles