Mdjon26
Mdjon26

Reputation: 2255

How to find out which radio button the user selected in Javascript?

I have a form that looks like this enter image description here

Right now, the problem I am having is that the user can select more than 1 radio button. They should only be able to select 1. I have a Javascript function that will go through all the rows and disable the button that was not selected as seen here.

function disableNonSelectedRadioButtons(selectedRadioButton) {
    $('#payer-contract-global-table .clone-target').each(function (i)  {
        var radioName = 'radio' + '-c' + i;
        if (selectedRadioButton != radioName)
            $('#' + radioName).prop("checked", false);
    });
}

This works. But I need to send the correct selectedRadioButton to this function. How can I correctly do that in Javascript?

Currently the HAML looks like this:

   %input.radio-button{:name => "radio-c#{index}", :type => "radio", :id => "radio-c#{index}", :checked => "true"}

Is there some type of code in Javascript that I can do that says that if I click button for radio-c2 it will send that to my function?

Upvotes: 2

Views: 136

Answers (3)

Tate Thurston
Tate Thurston

Reputation: 4660

If you want to use jQuery:

  $('input[type="radio"]').click(function(e){
       var selectedRadioName = $(this).attr('name');
       disableNonSelectedRadioButtons(selectedRadioName);
  });

If you're creating elements dynamically, use event delegation: https://learn.jquery.com/events/event-delegation/

 $(document).on('click', 'input[type="radio"]', function(e){
       var selectedRadioName = $(this).attr('name');
       disableNonSelectedRadioButtons(selectedRadioName);
 });

That said, you can just use HTML for this:

<input type="radio" name="giveThemAllTheSameName" />

By giving the radio buttons the same name you will only be able to select one.

Upvotes: 3

DIEGO CARRASCAL
DIEGO CARRASCAL

Reputation: 2129

If you encounter that the event is not being triggered, It happens because the DOM element are being generated dynamically (I think...) I solve it like this:

$(document).on('click', 'input[type="radio"]', function(e){
   var selectedRadioName = $(this).attr('name');
   disableNonSelectedRadioButtons(selectedRadioName);
});

just in case.

Upvotes: 2

Mateusz Bartkowski
Mateusz Bartkowski

Reputation: 729

You can use prop()

$('input[type="radio"]').click(disableNonSelectedRadioButtons($(this).prop('name')));

Upvotes: 0

Related Questions