0

I'm looking for a generalized solution for this.

Consider 4 radio type inputs with the same name. When submitted, the one that is checked determines the value that gets sent with the form:

I would like to have a text area displayed only at 1 and 3 : its always working only with value 1 and never value 3.

Below is the code snippet.

function getit() {
  var select = document.getElementById('f06_w01').checked;
  if (select == 1 || select == 3) {
    document.getElementById('whitch').style.display = "block";
  } else {
    document.getElementById('whitch').style.display = "none";
  }
}
<input type="radio" id="f06_w01" name="f06_w01" value="1" onchange="getit();" required />
<input type="radio" id="f06_w01" name="f06_w01" value="2" onchange="getit();" required />
<input type="radio" id="f06_w01" name="f06_w01" value="3" onchange="getit();" required />
<input type="radio" id="f06_w01" name="f06_w01" value="4" onchange="getit();" required />

<div id="whitch" style="display: none;">
  <p><b>Whats better?</b></p>
  <p><textarea name="f06_t02" id="f06_t02" cols="80" rows="3"></textarea></p>
</div>

How can I make this work?

Nik
  • 1,589
  • 2
  • 15
  • 23
freshminds
  • 23
  • 1
  • 1
  • 2

1 Answers1

2

You are not selecting the checked input radio, you are just picking the first element with that id, since id should be unique.

You can fix it actually selecting the checked input radio:

   function getit(){
        var select = document.querySelector('input[name="f06_w01"]:checked').value;
        if(select == 1 || select == 3) { document.getElementById('whitch').style.display = "block"; }
        else { 
            document.getElementById('whitch').style.display = "none"; 
        }
    }
<input type="radio" name="f06_w01" value="1" 
onchange="getit();" required />
<input type="radio" name="f06_w01" value="2" onchange="getit();" required />
<input type="radio" name="f06_w01" value="3" 
onchange="getit();" required />
<input type="radio" name="f06_w01" value="4" onchange="getit();" required />

<div id="whitch" style="display: none;">
<p><b>Whats better?</b></p>
<p><textarea name="f06_t02" id="f06_t02" cols="80" rows="3"></textarea></p>
</div>