changing the input class of a radio button dynamically with javascript

I am trying to make a small question web app using javascript/html. what I am trying to do is, assign a class to each of the radio buttons for each question-i.e. all the radio buttons for question 1 will have an input class of "question1" and 2 will have a class of "question2" and so on. Because I don’t know how many questions I will have, I was wondering if there was a way to achieve this dynamically through javascript using element.classList.add and increment the value of the question by 1 each time. I have received a response using jquery, but I was wondering if there was also a way to achieve this using pure javascript. After some research, I have tried accessing all the elements inside a form using "form.elements" however it does not seem to be working.

HTML:

<form name="quizForm">
    <div class="content">
        <div class="quiz">
        <p>Question 1</p>
        <input type="radio" name="answer" value="1">
        <input type="radio" name="answer" value="2">
        <input type="radio" name="answer" value="3">
        </div>

        <div class="quiz" style="display: none;">
        <p>Question 2</p>
        <input type="radio"  name="answer" value="1">
        <input type="radio"  name="answer" value="2">
        <input type="radio"  name="answer" value="3">
        </div>
    
        <div class="quiz" style="display: none;">
        <p>Question 3</p>
        <input type="radio" name="answer" value="1">
        <input type="radio" name="answer" value="2">
        <input type="radio" name="answer" value="3">
        </div>
</form>

Javascript:

//counting the index of the class
let ind =0;

//access the named elements within the form
let elements = form.elements;
for(i=0;i<elements.length;i++){
    element.classList.add(`quiz${ind+1}`)
}

Any information towards the right direction is greatly appreciated. Thank you.

23 thoughts on “changing the input class of a radio button dynamically with javascript”

  1. please check the following solution
    you can do this by selecting html tag in js
    these are different methods

    Javascript using DOM:

    // Check
    document.getElementById("checkbox").checked = true;
    
    // Uncheck
    document.getElementById("checkbox").checked = false;
    

    or other libraries like jquery

    jQuery (1.6+):

    // Check
    $("#checkbox").prop("checked", true);
    
    // Uncheck
    $("#checkbox").prop("checked", false);
    

    jQuery (1.5-):

    // Check
    $("#checkbox").attr("checked", true);
    
    // Uncheck
    $("#checkbox").attr("checked", false);
    

    #Copied
    or the others selector like querySelectorAll

    Reply

Leave a Comment