Search code examples
javascriptformsradio-button

Add to a variable each time a radio btn is checked?


I have 2 variables and 3 radio btns. I want 1 to be added to one of the 2 variables each time a radio is checked (if it is radio #1 or #3 then it should be added to var countA, or else should be added to countB). I only want to use Javascript (not jQuery) and there must be something wrong with my code bc the paragraphs do not change their inner HTML to the values of countA and countB when the button i clicked. JAVASCRIPT:

var countA = 0
            var countB = 0
            function check() {
                var 1 = document.getElementById("1").checked
                var 2 = document.getElementById("2").checked
                var 3 = document.getElementById("3").checked
                var radios = document.getElementsByTagName("input")
                
                for (var i=0; i<radios.length; i++) {
                
                if (1 == true) {
                    countA++
                }
                if (2 == true) {
                    countB++
                }
                if (3 == true) {
                    countA++
                }
                }
            document.getElementById("p").innerHTML = countA
            document.getElementById("p2").innerHTML = countB
            
            }

HTML:

<input type = "radio" id="1" class="a">
        <input type="radio" id="2" class="b">
        <input type="radio" id="3" class="a"><br>
        CountA: <p id="p"></p>
        CountB: <p id="p2"></p><br>
        <button id="btn" oncick="check()">Click</button>

Solution

  • You can get the id of radio button which is selected and increment the value of count depending on that.Also, you have not given name to your radio button give them so at a time only one button can get clicked .

    Demo Code :

    var countA = 0
    var countB = 0
    
    function check() {
    //getting length
      var radios = document.getElementsByTagName('input').length
     var selctor=document.getElementsByTagName('input');
      for (var i = 0; i < radios; i++) {
      //checking if radio is checked
       if (selctor[i].checked) {
       console.log("id-->"+selctor[i].getAttribute('id'))
       //checking id 
        if (selctor[i].getAttribute('id') == 1 || selctor[i].getAttribute('id') == 3) {
          countA++
        }
        if (selctor[i].getAttribute('id') == 2) {
          countB++
        }
       
        }
      }
      document.getElementById("p").innerHTML = countA
      document.getElementById("p2").innerHTML = countB
    
    }
    <input type="radio" id="1" class="a" name="radio" >
    <input type="radio" id="2" class="b" name="radio">
    <input type="radio" id="3" class="a" name="radio"><br> CountA:
    <p id="p"></p>
    CountB:
    <p id="p2"></p><br>
    <button id="btn" onclick="check()">Click</button>