单选按钮选择使用 JS 而非 ONCLICK 驱动 div 可见性

问题描述 投票:0回答:0

我有一些部分有效的 html 代码。我试图根据单选按钮选择显示一些文本输入。我让它工作,当按下单选按钮时它确实隐藏了其他选项,但在屏幕的第一次加载时显示所有 3 个选项。我假设它是因为单击时调用了该函数,并且第一个单选按钮的选中选项不构成单击。我试图制作一个 onload 事件侦听器,它只会以我第一次请求的状态显示,但没有用。 这是我的代码

<% layout('layouts/boilerplate') %>
    <h1>New Part</h1>
    <form action="/parts" method="POST" novalidate class="validated-form">
        <div>
            <label class="form-label" for="partnum">Part Number</label>
            <input  class="form-control" type="text" name="part[partnum]"  id="partnum" required>
        </div>
        <div>
            <label class="form-label" for="description">Part  Description</label>
            <input class="form-control" type="text" name="part[description]"   id="description" required>
        </div>
        <div class="btn-group" role="group" aria-label="Basic radio toggle button group">
            <input type="radio" class="btn-check" name="part[type]" id="btnradio1" value="Purchased" autocomplete="off"  onclick="show1()" checked >
            <label class="btn btn-outline-primary" for="btnradio1">Purchased</label>
          
            <input type="radio" class="btn-check" name="part[type]" id="btnradio2" value="Assembly" autocomplete="off" onclick="show2()">
            <label class="btn btn-outline-primary" for="btnradio2">Assembly</label>
          
            <input type="radio" class="btn-check" name="part[type]" id="btnradio3" value="Machined" autocomplete="off" onclick="show3()">
            <label class="btn btn-outline-primary" for="btnradio3">Machined</label>
          </div>
          <div>
            <h1 id="test1">Test 1</h1> 
          </div>
          <div>
            <h1 id="test2" >Test 2</h1>
          </div>
          <div id="machined">
            <h1 id="test3" >Test 3</h1>
            <div>
                <label class="form-label" for="material">Material</label>
                <input  class="form-control" type="text" name="part[material]"  id="material" required>
            </div>
          </div>
          <div><button>Add  Part</button></div>    
    </form>
    <a href="/parts">Back to your Parts</a>

    <script>  
function show1(){
  document.getElementById('test1').style.display ='block';
  document.getElementById('test2').style.display ='none';
  document.getElementById('machined').style.display ='none';
}
function show2(){
  document.getElementById('test1').style.display ='none';
  document.getElementById('test2').style.display ='block';
  document.getElementById('machined').style.display ='none';
}
function show3(){
  document.getElementById('test1').style.display ='none';
  document.getElementById('test2').style.display ='none';
  document.getElementById('machined').style.display ='block';
}
  
    </script>
javascript html ejs bootstrap-5
© www.soinside.com 2019 - 2024. All rights reserved.