Radio inputs created with a loop in jQuery all being assigned the same value

First time posting here. I am trying to make a movie recommender that presents the user with a set of movies to rate on a radio scale of 1-10 with a "No Rating" button if they haven’t seen the movie. I have been trying to loop over all of the checked buttons to get their values, but they are all coming up as the value assigned to the first "No Rating" button in the radio input, which is appended to the table before the inner loop executes. Can anyone shed some light on what’s going on? I don’t have much experience in JS or jQuery and have had my brother helping me along the way. Here is my code:

for (let i = 0; i<keys.length; i++) {
...
    let $movieRating = $('<tr class="rating-row">')
...
// Add initial "No Rating" button
    let $ratingButton = $('<td>');
    $ratingButton.append($(`<input type="radio" class="ratButton" id="rating${i}-0"
      name="rating${i}" value=null><label for="rating${i}-0">No Rating</label>`));
// Add 1-10 buttons   
    for (let j=1; j <= 10; j++) {
        $ratingButton.append($(`<input type="radio" class="ratButton" id="rating${i}-${j}"
          name="rating${i}" value="${j}"><label for="rating${i}-${j}">${j}</label>`));
    }
    $movieRating.append($ratingButton);
    $("table tbody").append($movieRating);

I have the value set to null for the "No Rating" button, and then the 1-10 buttons are supposed to have the value set to the ${j}. I am pulling the values with:

$('.rating-row').each(function(idx, row) {
    let $radioButton = $(row).find('input:radio');
    if ($radioButton.is(':checked')) {
        let radioVal = $radioButton.val();
         console.log(radioVal);
    }
})

radioVal is always coming up null, no matter what is checked. I hope this is clear. Tips on formatting welcome as well. Thanks a lot!

23 thoughts on “Radio inputs created with a loop in jQuery all being assigned the same value”

Leave a Comment