简体   繁体   中英

How to get different value from radio button?

I want the rate to change when I select different currency. But right now it only show my initial checked value. Here my code

 let btn = document.querySelector("button"); let priceDisplay = document.querySelector("#price"); let currency = document.querySelector('input[name=rate]:checked').value; btn.addEventListener("click",function(){ let XHR = new XMLHttpRequest(); XHR.onreadystatechange = function(){ if(XHR.readyState == 4 && XHR.status==200){ let data = JSON.parse(XHR.responseText); let price = data.bpi[currency].rate; priceDisplay.innerText = price + " " + currency; } } XHR.open("GET","https://api.coindesk.com/v1/bpi/currentprice.json"); XHR.send(); })
 <h1>Bitcoin Current Price is: <span id="price"></span></h1> <p>Pick your currency: </p> <input type="radio" id="USD" name="rate" value="USD" checked> <label for="USD">USD</label><br> <input type="radio" id="GBP" name="rate" value="GBP"> <label for="GBP">GBP</label><br> <input type="radio" id="EUR" name="rate" value="EUR"> <label for="EUR">EUR</label><br> <button>Refresh Data</button>

You need to put the querySelector() code

btn.addEventListener("click",function() {
    let currency = document.querySelector('input[name=rate]:checked').value;
    ....
}

inside the click event handler. The reason is because it's executed only once before the click event triggered, so it got only 1 first checked value. When you click the button, it needs new updated value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM