You are viewing limited content. For full access, please sign in.

Question

Question

Forms - Jquery to copy index of one radio to another?

asked on September 24, 2021

I am trying to get the index of a radio button, so that I can copy it to another radio button in a different language.

However every example online of how to get a index of a selected radio button requires this name attribute. All we have in forms is classes to work with, so how do I get the name attribute?

How would you go about setting this "radioFieldName" in Forms in addition to the class?

var radioButtons = $(".myClassRadioClass input:radio[name='radioFieldName']");
var selectedIndex = radioButtons.index(radioButtons.find(':checked'));
0 0

Answer

SELECTED ANSWER
replied on September 27, 2021

If you have the same number of radio buttons in each group and they're in the same order, the easiest solution would be to just loop through them and copy their states over.

// iterate all radio inputs in first set
$('.radioSet1 input').each(function(index, value){
      // copy state to corresponding input in second set
      $('.radioSet2 input').eq(index).prop('checked',$(this).prop('checked'));
});

 

0 0
replied on September 29, 2021

This works perfectly. I don't even see where the variable index is being set, but it does work. 

Both radios will have the same number of indexes, they are just in different languages and I need to copy the values to a shared field for reporting in one language.

 

Thanks!

0 0
replied on October 4, 2021

Hi Chad,

So you'll know for future tasks, the .eq() function after the selector is what is setting the index, it can also be used with a negative number to select from the end.

.eq() | jQuery API Documentation

0 0
replied on October 4, 2021

Oh I meant that the variable "index" used as a parameter for that function does not seem to be populated anywhere here.

 

It is a parameter to the function, and a parameter to the eq method, but we never populate it.

0 0
replied on October 4, 2021

Ah gotcha, that's part of the $.each() method.

When you use $.each(function(index, element){})

index and value/element will populate automatically as long as you define the variable names in the function parameters.

.each() | jQuery API Documentation

Technically you don't need the "value" variable I included for the element, I just put it in out of habit.

1 0
replied on October 4, 2021

This is useful! Thank you!

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.