How to make a row of radio buttons single-select using HTML and jQuery?



  • Hello,

    I'm creating a trivia game with JS and jQuery, and I'm trying to make my radio buttons be single-select per question. Right now they are acting like checkboxes. How would I do this? I'm using Bootstrap to create the radio buttons and running a for loop to append them to each question.

    var surveyQuestions = [
    {
    question: "1.) The design for Pac-Man was originally inspired by a...",
    answers: ["Cheese wheel", "Pizza", "Pie chart", "Grapefruit"],
    correctAnswer: "Pizza"
    }
    ];

    var survey = {
    totalScore: 0,
    correctAnswers: 0,
    incorrectAnswers: 0,
    questions: surveyQuestions,

    showSurvey: function () {

    for (i = 0; i < survey.questions.length; i++) {
        console.log(survey.questions[i]);
    
        $(".questions-text").append("<p><strong>" + survey.questions[i].question + "</strong></p>")
    
        for (j = 0; j < survey.questions[i].answers.length; j++) {
            var userChoices = survey.questions[i].answers[j];
            $(".questions-text").append("<div id='option_" + i + j + "'></div>");
            $(".questions-text").append("<p>" + userChoices + "</p>")
            var radioBtn = $('<input type="radio" name="' + userChoices + '" id="' + i + j + '"/>');
            radioBtn.appendTo('#option_' + i + j);
        }
    

    }



  • @Cairoshock said in How to make a row of radio buttons single-select?:

    option_

    Hey @Cairoshock

    The reason is for that is because the value for the 'name' attribute has to be the same for each set of options.

    Check out the following W3 School example:

    https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio

    Here is what I suggest:

    So change the following line

    var radioBtn = $('<input type="radio" name="' + userChoices + '" id="' + i + j + '"/>');
    
    var radioBtn = $('<input type="radio" name="question_' + i + '" id="' + i + j + '" value="' + userChoices + '/>');
    

    Then make sure you get the correct userChoices value by calling .val() (jQuery) or .value (vanilla javascript)



  • @Cairoshock said in How to make a row of radio buttons single-select?:

    option_

    Hey @Cairoshock

    The reason is for that is because the value for the 'name' attribute has to be the same for each set of options.

    Check out the following W3 School example:

    https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio

    Here is what I suggest:

    So change the following line

    var radioBtn = $('<input type="radio" name="' + userChoices + '" id="' + i + j + '"/>');
    
    var radioBtn = $('<input type="radio" name="question_' + i + '" id="' + i + j + '" value="' + userChoices + '/>');
    

    Then make sure you get the correct userChoices value by calling .val() (jQuery) or .value (vanilla javascript)



  • @avantutor This works, thank you!


Log in to reply