Domanda

I'm trying to find the best way of checking a url based on a radio button selection. On my page, I have at least 5 pairs of radio buttons. Can someone tell me what's the best way of sending the user to the correct url based on their selected radio button?

$(document).ready(function () {
    $("*[type=radio]").change(function () {
       alert( $(this).attr("value"))
    })
});

see more code: jsfiddle

È stato utile?

Soluzione

Based on your jsfiddle, your radio button pairs are named in sequential order: the first pair is named 1, the second pair is named 2, and so on. You can use this to assign a listener to the buttons in a loop. First, give each button an id that matches the radio button group name, and a class to identify them as a group, as follows:

<div>
    <ul>
        <li>
            <input type="radio" name="1" value="http://www.google.com" checked="checked" id="radio-1">
            <label for="radio-1"><strong>link 1</strong></label>
        </li>
        <li>
            <input type="radio" name="1" value="http://www.bing.com" id="radio-2">
            <label for="radio-2"><strong>link 2</strong></label>
        </li>
    </ul>
</div>
<p>
    <button id='button_1' href="#" class="radio-redirect btn btn-primary">GO !</button>
</p>

So you'll end up with a bunch of those buttons. Then you need to loop through them and give them a listener:

$.each($('.radio-redirect'), function(i, item) {
    var id = $(item).prop('id');
    var idparts = id.split('_'); // idparts[1] is now the number portion of the id
    $(item).click(function() {
        location.href=$('input[name='+idparts[1]+']:checked').val();
    });
});

Here's a jsfiddle where I've replaced the location.href assignment with an alert call, so that the frame that contains the executing code won't go away. As long as you are consistent with your naming standard, this will work. If you change your radio button names to, say radiobutton_1 instead of simply 1, you just modify the location.href line to incorporate the full name.

If you are not consistent with your naming, then you'll have to manually assign the click events to each button, rather than being able to do it in a loop. But it can still be done.

Altri suggerimenti

I would do it like this:

$(document).ready(function () {
    $("input[type=radio]").change(function () {
       alert( $(this).val() )
    });
});

there can only be input's of type=radio, so is much faster selecting it by tagName.

the trick is probably to use on() listener - http://jsfiddle.net/mMNUE/3/

$(document).ready(function () {
    $("*[type=radio]").on('change', function () {

         alert( $(this).val());

    })
})

and use val(); instead of attr();

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top