1

I have a foreach that contain 3 radio buttons, how do I enable a specific button when the radio button is checked? I have this:

// Starts by disabling all the buttons
$('.btn-portabilizar').attr('disabled', true);

// If it is checked, enable the a specific button
$('input[name="autorizacao"]:checked').click(function(){
   $('.btn-portabilizar').removeAttr('disabled');
});

And my view is this:

<% @autorizacoes.each do |autorizacao| %>
    <tr>
        <td><%= radio_button_tag 'autorizacao', autorizacao.numero_contrato %></td>
        <td><%= autorizacao.numero_contrato %></td>
        <input class="string required" type="text" name="portabilidade_nova_parcela" id="portabilidade_nova_parcela">
        </td>
        <td>
            <%= link_to "Portabilizar", "#", :class => 'btn btn-primary btn-portabilizar' %>
        </td>
    </tr>
<% end %>

Sorry for code in portuguese...

UPDATE ==========================================

When checked enable button, when unchecked disable button, I do it, but don't work:

  $('input[name="autorizacao"]').click(function(){
    if (this.checked) {
      $(this).closest('tr').find('.btn-portabilizar').prop('disabled', false);
    }
    else
      $(this).closest('tr').find('.btn-portabilizar').prop('disabled', true);

  });

What is my wrong?

Elton Santos
  • 571
  • 6
  • 32

1 Answers1

2

Your radio button selector is incorrect - you only attach it to radio buttons which are already checked on load, of which I'm assuming there are none. Remove the :checked part:

$('input[name="autorizacao"]').click(function(){
    $('.btn-portabilizar').prop('disabled', false);
});

Also note that it's better practice to use prop() where possible.

To only affect the button in the same row you would need to use jQuery's DOM traversal methods, like this:

$('input[name="autorizacao"]').click(function(){
    $(this).closest('tr').find('.btn-portabilizar').prop('disabled', false);
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339