Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect browser based on radio button value

Is there an easier way to redirect the browser based on the selection from a radio button? This works but from what I'm reading on the world wide web there is probably 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

like image 608
brandozz Avatar asked Feb 23 '13 17:02

brandozz


1 Answers

I would change the html just 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 change to the .on() method since it simply makes a call to .on() anyways. The reason is that .click() simply makes a call to the .on() method creating one extra function call that isn't really necessary. Plus .on() is much more flexible!

like image 147
Tom Bird Avatar answered Oct 27 '22 03:10

Tom Bird