Isaac Reefman
Isaac Reefman

Reputation: 597

How do you reference the checked value in a radio input control for a javascript function?

I need the output element of an html form to display content that is based off whatever item is checked from a radio button set. When I only need to display which value is checked it works fine, but when I try to use a function to switch the output, the if statement doesn't work - the function always returns 'Farenheit' as though option.value remains 'celcius' (regardless of how often the option buttons are swapped):

<script>
    function switchOpt(opt){
        if (opt='celcius'){
        return 'Farenheit';
        }else{
        return 'Celcius';
        }
    }
</script>
<form oninput="swap.value=switchOpt(option.value)">
    <input type="radio" name="option" value="celcius" checked /> Celcius <br />
    <input type="radio" name="option" value="farenheit" /> Farenheit <br />
    <output name="swap"></output>
</form>

The same setup for the if statement works in other functions, so I'm guessing the problem is that there's a datatype mismatch or something in how I'm trying to refer to the values here.

How do you refer to the checked value in a set of radio buttons within a function?

Upvotes: 0

Views: 46

Answers (2)

ConsoleLog
ConsoleLog

Reputation: 511

function switchOpt(opt) {
  if (opt == 'farenheit') {
    return 'Farenheit';
  } else {
    return 'Celcius';
  }
}
<form oninput="swap.value=switchOpt(option.value)">
  <input type="radio" name="option" value="celcius" checked /> Celcius <br />
  <input type="radio" name="option" value="farenheit" /> Farenheit <br />
  <output name="swap"></output>
</form>

Note the change in the if condition...

=== operator checks both value and type whereas == only compares the value. For example, 3 == '3' will return true even though one is a string and the other is a number and to avoid this should use ===. Therefore, I’d say it’s safer to use the former although I did use == here :) Single = is for assigning. For example var x = document.getElementById(‘box’);

Upvotes: 2

Emil Alkalay
Emil Alkalay

Reputation: 496

You should use === in your if clause instead of =.

In addition always add labels for your radio buttons and checkboxes.

<script>
    function switchOpt(opt){
        if (opt==='celcius'){
        return 'Farenheit';
        }else{
        return 'Celcius';
        }
    }
</script>
<form oninput="swap.value=switchOpt(option.value)">
    <input type="radio" name="option" id="celcius" value="celcius" checked /> <label for="celcius">Celcius</label> <br />
    <input type="radio" name="option" id="farenheit" value="farenheit" /><label for="farenheit"> Farenheit</label> <br />
    <output name="swap"></output>
</form>

Upvotes: 0

Related Questions