1

I have a list that has 2 radio buttons against it. I need to randomly select radio buttons in that list. Each radio button (rb1: yes and rb2: no) has different ids. Here's my code.

$("#rbList").each(function () {                                                                
            var radios = $(this).find("input[type=radio]");
            if (radios.length > 0) {
                var randomnumber = Math.floor(Math.random() * radios.length);
                $(radios[randomnumber]).trigger('click');
            }
        });

This works to select one radio button in the group. What I don't understand is how to loop it to randomly select all the radio buttons in the list (be it either yes or no). What do I have to add? Also, I need to automate that. Like just hit enter in console and it should reflect on the page. Any help is greatly appreciated. Thank you.

Anan Srivastava
  • 112
  • 1
  • 9
  • 1
    http://stackoverflow.com/questions/5665915/how-to-check-a-radio-button-with-jquery Check here. Don't need to trigger a click on it, only set the attr/prop. – mvc_help Jan 11 '17 at 09:47
  • 1
    Try `radios.eq(randomnumber).prop("checked", true)` better if you can share HTML – Satpal Jan 11 '17 at 09:48
  • Instead of the `$.each` set on the `#rbList`, set it on the common class for each group. – artur99 Jan 11 '17 at 09:58
  • And you are looping through an element whose length is ONE. – Jai Jan 11 '17 at 09:58

1 Answers1

0

Use this for triggering check and uncheck

$("#YourRadioID").prop("checked", true)

In your Case :

       $("#rbList").each(function () {                                                                
            var radios = $(this).find("input[type=radio]");
            if (radios.length > 0) {
                var randomnumber = Math.floor(Math.random() * radios.length);
                $(radios[randomnumber]).prop("checked", true);
            }
        });

for older version you have to use

$("#YourRadioID").attr('checked', 'checked');
danish farhaj
  • 1,316
  • 10
  • 20
  • `$("#rbList").each`.....Really? If it just one element then looping is not required. – Jai Jan 11 '17 at 09:58