How do I make a text field/select option visible/invisible by selecting a radio button option in HTML?

StackOverflow https://stackoverflow.com/questions/22867039

  •  27-06-2023
  •  | 
  •  

質問

<!DOCTYPE html>
<html>
   <body>
      <form>
         /*yes or no radio button option*/ 
         Deduction: <input type="radio" name="option" value="yes">Yes
         <input type="radio" name="option" value="no">No
         <br>

         /* text field for the amount if yes is selected, if no is selected the amount*/ 
         /* and the affiliate selection shouldn't be showing*/ 
         Amount:<input type="text" name="amount">
         <br>
            <select>
               <option value="affiliate">Select Affiliate</option>
               <option value="x">x</option>
               <option value="y">y</option>
            </select>
         <br>
         <br>
         <input type="submit" value="Submit">
         <br>
      </form>
   </body>
</html>

So basically if no is selected there is only the submit button. If yes is selected the amount text field is shown and the selected affiliate is shown as well.

役に立ちましたか?

解決

To my knowledge you can't do this with just HTML. A JavaScript solution entails. You can enable and disable divs with ease, full example below:

<html>
<head>

<script type="text/javascript"> 
function Reveal (it, box) { 
var vis = (box.checked) ? "block" : "none"; 
document.getElementById(it).style.display = vis;
} 

function Hide (it, box) { 
var vis = (box.checked) ? "none" : "none"; 
document.getElementById(it).style.display = vis;
} 
</script>
</head>
<body>

<form>
<input type="radio" name="mype" value="ve1" onClick="Hide('div2', this); Reveal('didfv1', this)" />value1

<input type="radio" name="mype" value="value2" onClick="Hide('didfv1', this); Reveal('div2', this)" />value2

<input type="checkbox" name="modtype" value="value3" onClick="Reveal('div3', this)" />value3

<input type="checkbox" name="modtype" value="value4" onClick="Reveal('div4', this)" />value4

<input type="checkbox" name="modtype" value="value5" onClick="Reveal('div5', this)" />value5

</form>


<div class="row" id="didfv1" style="display:none">Show Div 1</div>
<div class="row" id="div2" style="display:none">Show Div 2</div>
<div class="row" id="div3" style="display:none">Show Div 3</div>
<div class="row" id="div4" style="display:none">Show Div 4</div>
<div class="row" id="div5" style="display:none">Show Div 5</div>

</body>

</html>

This is tested and working, more here: http://www.webdeveloper.com/forum/showthread.php?205055-Div-Hide-Show-using-Radio-Buttons

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top