JavaScript I have to click twice to select to element

Viewed 150

Please anyone can help to fix the issue with my code, sometimes I have to click twice to select the next elements

var varientbtn = document.getElementsByClassName('clickthisbtn');

    for(let i = 0; i < varientbtn.length; i++) {
        varientbtn[i].onclick = function () {
          
            const rbs = document.querySelectorAll('input[name="choice"]');
            let selectedValue;
            let varientSelectedPrice;
          
            for (const rb of rbs) {
              if (rb.checked) {
                selectedValue = rb.value;
                varientSelectedPrice = rb.getAttribute("data-price");
                break;
              }
            }
            document.getElementById('log').innerHTML = selectedValue;
            document.getElementById('varientprice').innerHTML = varientSelectedPrice;
            console.log(selectedValue, varientSelectedPrice);
        }
    }

Live preview: https://codepen.io/Elkazi/pen/wvJeErg

2 Answers

That's because when one of labels be clicked, the checked value of related radio still not change.

Try this

 const rbs = document.querySelectorAll('input[name="choice"]');

    for(let i = 0; i < rbs.length; i++) {
        rbs[i].addEventListener('change', function () {
            let selectedValue;
            let varientSelectedPrice;
          
            for (const rb of rbs) {
              if (rb.checked) {
                selectedValue = rb.value;
                varientSelectedPrice = rb.getAttribute("data-price");
                break;
              }
            }
            document.getElementById('log').innerHTML = selectedValue;
            document.getElementById('varientprice').innerHTML = varientSelectedPrice;
            console.log(selectedValue, varientSelectedPrice);
        });
    }

    rbs[0].dispatchEvent(new Event('change'));

Since you are adding event listener to the label element, you should make use of its for attribute to get the related input field. That way you don't have to run a loop for all inputs and will always get the latest/correct value.

this will point to the element on which the event handler is called.



var varientbtn = document.getElementsByClassName('clickthisbtn');

    for(let i = 0; i < varientbtn.length; i++) {
        varientbtn[i].onclick = function () {
         let relatedInput = document.getElementById(this.getAttribute("for"));
            let selectedValue = relatedInput.value;
            let varientSelectedPrice = relatedInput.getAttribute("data-price");;
            document.getElementById('log').innerHTML = selectedValue;
            document.getElementById('varientprice').innerHTML = varientSelectedPrice;
            console.log(selectedValue, varientSelectedPrice);
        }
    }


Related