BiPi Singh
BiPi Singh

Reputation: 11

I can not read the value of a non-default radio button when checked in JS

I am trying to read the value of radio buttons. The first radio is checked by defaults and I can read its value. When I check the second button with value="USA", it still returns value="UK".

var countryName = document.querySelector("input[name=userCountry]:checked");

function adjustMeasurements() {
  if (countryName.value == "UK") {
    alert("User lives in UK.");
  } else {
    alert("User lives in USA.");
  }
}
<input type="radio" name="userCountry"  value="UK"  checked="checked" required="required" /> 
<input type="radio" name="userCountry"  value="USA" />

Upvotes: 1

Views: 29

Answers (2)

Matus Dubrava
Matus Dubrava

Reputation: 14482

The problem with your code is that you execute it only once when the script is loaded. To make it responsive and trigger your alerts each time you make a new selection, you need to specify an event listener and pass your function as a callback to this listener (or trigger it inside of a callback).

function adjustMeasurements(countryName) {
  if (countryName == "UK") {
    alert("User lives in UK.");
  } else {
    alert("User lives in USA.");
  }
}

const inputs = document.querySelectorAll('input');
inputs.forEach(item => {
  item.addEventListener('change', event => {
    adjustMeasurements(event.target.value);
  });
});
<input type="radio" name="userCountry"  value="UK"  checked="checked" required="required" />
<input type="radio" name="userCountry"  value="USA" /> 

And if your only goal is to achieve this functionality - alerting location based on the selected value, then you can omit the adjustMeasurements function completely and do just this.

const inputs = document.querySelectorAll('input');

inputs.forEach(item => {
  item.addEventListener('change', event => {
    alert(`User lives in ${event.target.value}`)
  });
});
<input type="radio" name="userCountry"  value="UK"  checked="checked" required="required" />
<input type="radio" name="userCountry"  value="USA" /> 

Upvotes: 1

Thomas
Thomas

Reputation: 442

You need to put the line:

var countryName = document.querySelector("input[name=userCountry]:checked");

inside of your function. You're setting the variable and never changing it, so whatever your default checked value is, is what you're sticking to forever.

Once inside your function, it will update the variable each time it's run. This will give you the correct result.

function adjustMeasurements()
{
    var countryName = document.querySelector("input[name=userCountry]:checked");

    if (countryName.value == "UK") {
        alert("User lives in UK.");
    } else {
        alert("User lives in USA.");
    }
}

Upvotes: 0

Related Questions