javascript - Rediriger le navigateur en fonction de la valeur du bouton radio


Y a-t-il une façon plus facile de rediriger le navigateur en fonction de la sélection d'un bouton radio ? Cela fonctionne, mais d'après ce que je lis sur le web, il y a probablement une manière plus simple.

Voici mon formulaire :

<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>

Voici mon 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");
    }
});});

Merci d'avance

Réponse #1

Je changerais un peu le HTML pour quelque chose comme ceci :

<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>

Je changerais aussi pour la méthode .on() puisque cela appelle de toute façon simplement .on(). La raison est que .click() appelle simplement la méthode .on(), créant un appel de fonction supplémentaire qui n'est pas vraiment nécessaire. De plus, .on() est beaucoup plus flexible !

Réponse #2

DÉMO EN DIRECT

$(function() {

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

});