mercredi 3 février 2021

JavaScript swapping inputted values of radio buttons

I'm a beginner making my first JavaScript app. Its a diet app designed to calculate the user's BMR (calories burned in 24 hrs). For it to work, the user needs to enter their height and weight. I want to give the user the opportunity to enter these details in Imperial units or Metric units.

I've designed a simple HTML form. The form has two radio buttons, one for Imperial and one for Metric. The HTML is:

<input type="radio" checked="checked" id="imperial" name="measurement" value="imperial"><label for="imperial">Imperial</label>

<input type="radio" id="metric" name="measurement" value="metric"><label for="metric">Metric</label>

Because I live in the UK, and because most people here still use Imperial units for their height and weight, I added checked="checked" to the first input tag to pre-select the Imperial radio button.

In the JavaScript I used the following line to assign both radio buttons to the same variable:

const units = document.getElementsByName("measurement");

I console logged units and, as expected, the value was a node list with two items. This is the console output:

NodeList(2) [input#imperial, input#metric]
0: input#imperial
1: input#metric
length: 2

As you can see, Imperial is first in the list, at position zero. I wanted to use this to assign the user's choice to a different variable, which I could then use later on. For this, I created the following if statement:

for(i = 0; i < units.length; i++) {
    if(units[i].checked) {
      unitUsed = "imperial";
    } else {
      unitUsed = "metric";
    }
  }

Let's say the user has opted not to click the Metric radio button. Imperial will still be checked. The first time the loop runs, it asks "Is the item at position zero in the node list checked? The answer should be 'yes'. Therefore, the variable unitUsed should be given "Imperial" as a value.

However, when I console.log(unitUsed) it tells me the value is Metric. And when I submit the form again and choose Metric, JS tells me the value of unitUsed is Imperial. It's doing the exact diametric opposite of what I want.

I've been staring at this for half an hour and I can't see the flaw in the logic. Can anyone help me out? Many thanks.

Aucun commentaire:

Enregistrer un commentaire