Darren
Darren

Reputation: 21

Disable radio buttons based on the action of other radio buttons

This works perfectly for one set of 3 radio buttons:

$("input:radio").click(function() {
    $(this).siblings("input:radio").attr("disabled","disabled"); 
});

To take this one step further...I have 3 sets of 3 radio buttons:

1 2 3

1 2 3

1 2 3

if a user checks number 1 on line one I want it to disable number 1 on lines two and three...basically I'm giving a user 3 choices for each line and I want them to rank them and want all ranking to be different. Make sense?

Is this possible?

Upvotes: 1

Views: 4245

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124558

You'll need an easy way to select the other radio buttons. It sounds from your description that the values for all radio buttons with the same label will also have the same value, so you can select on that.

Group your radio buttons in divs with a shared class:

<div class="rating">
    <input type="radio" name="group1" value="1" />1
    <!-- more radio buttons -->
</div>
<div class="rating">
    <input type="radio" name="group2" value="1" />1
    <!-- more radio buttons -->
</div>
<!-- more radio button groups -->

You can now select the other radio button groups and disable all radio buttons with the same value:

$("input:radio").click(function() {
    var $this = $(this);
    var value = $this.val();
    $this.closest('.rating') # Parent div
        .siblings('.rating') # All the sibling divs, not this group
        .find('input:radio[value="' + value + '"]') # All radio buttons with the same value
        .attr("disabled", "disabled"); 
});

Alternatively, you can use the not filter to remove the current input selector from the group:

$("input:radio").click(function() {
    var $this = $(this);
    var value = $this.val();
    $('input:radio[value="' + value + '"]') # All radio buttons with the same value
        .not(this) # Explicitly remove the current radio button
        .attr("disabled", "disabled"); 
});

Upvotes: 1

Richard Dalton
Richard Dalton

Reputation: 35793

This will match all other radiobuttons on the page with the same value as the one you selected and disable them while also disabling the others in the current group.

$("input:radio").click(function() {
    var val = $(this).val();
    $(this).siblings("input:radio").attr("disabled","disabled"); 
    $("input:radio[value='" + val + "']").not(this).attr("disabled","disabled"); 
});

And like Felix said, this will make it so you can't change your selection once all options have been chosen. So I'd recommend you have a reset button.

Here is a jsfiddle example: http://jsfiddle.net/X6zKa/

Upvotes: 1

Related Questions