0

I need to select radio buttons with similar unique_id when I select one of the existing radio buttons. Here is the code:

$('.test li input:radio').change(function () {

    var unique_id = $(this).attr('unique_id');
    $('input:radio').each(function () {

        if ($(this).attr('unique_id') == unique_id) {
            $(this).attr('checked', true);
        } else {
            $(this).attr('checked', false);
        }

    });
});

Fiddle

In google chrome it is working but not always. It may work and may not work. Try to select radios many times. In Mozilla it doesn't work at all. What am I to do?

John Smith
  • 1,204
  • 3
  • 22
  • 42

2 Answers2

0

$('.test li input[type="radio"]').change(function(evt){

var other_el= $('.test li input[type="radio"][unique_id="' + $(evt.target).attr('unique_id') + '"]').not($(evt.target));


if (other_el.length === 1){
    other_el.attr('checked', $(evt.target).has(':checked')); 
}

});

here is a link: http://jsfiddle.net/Sj4Ah/1/

Enjoy!

user1271518
  • 636
  • 1
  • 9
  • 25
  • Thank you for your answer, but here is the same problem as in my code. Try to select radio-buttons many times. In Mozilla sometimes it is working and sometimes is not. – John Smith Aug 09 '13 at 05:59
0
$('.test li input:radio').change(function(){
    $('input[unique_id="'+$(this).attr('unique_id')+'"]').prop('checked', true);
});

Fiddle

Browsers automatically un-check radio inputs when another radio with the same name property is checked, so as long as all your radio groups have the same unique_id items you don't have to do that manually. Also the change event only fires for a radio input when it is checked, hence you just have to check all radios with the same unique_id attribute when one changes to keep the groups synced.


As for why your original code wasn't working in Firefox, you should use .prop() to set the checked property. Avoid using .attr() to set DOM element properties. See your original fiddle now using .prop(). I can't find any logic mistake besides that, though it can be further simplified setting the checked property with vanilla JS:

$('.test li input:radio').change(function(){
    var unique_id = $(this).attr('unique_id');
    $('input:radio').each(function(){
        this.checked = $(this).attr('unique_id') == unique_id;
    });
});

Fiddle


This question has received an answer on CodersClan.

Community
  • 1
  • 1
Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166