首页 > 解决方案 > 使用 Javascript 显示 Div 无法在 Select 上工作

问题描述

如果用户在 select 语句中选择了医生值,我将尝试显示 FILE DIV。我知道 if 语句有效,因为我还在控制台中打印了该值,它工作得非常好。我在我的其他网页中以相同的方式切换我的 div,所以我不明白这个网页发生了什么。

function viewFile(){
        var file = document.getElementById("doclicense");
        var type = document.getElementById('accountType').value;
        if(type === 'doctor') {
            file.style.display = "block";
            console.log(type);
        } 
    }
.hidden{
display : none;
}
<div> 
<select id="accountType" name="type" class="form-control" onchange="viewFile()"> 
<option required>Account Type</option>
                        <option value="doctor" name="doctor" id="doctor">Doctor</option>
                        <option value="regular" name="regular" id="reg">Regular Account</option>
                    </select>
</div>

                <div class="hidden file" id="doclicense">
                    <input type="file" name="license"  />
                    <input type="submit"/>
                </div>

******************************************编辑解决方法******** ***************

由于我的代码拒绝工作,我添加了一行代码,标题是“head”,而不是真正的值。感谢所有做出贡献的人。我完全取出了隐藏类,但是当我添加它时,它仍然无法正常工作。

 function viewDocFile() {
        var file = document.getElementById("doclicense");
        var type = document.getElementById('accountType').value;
        if (type === 'regular' || type === 'head') {
            file.style.display = "none"; 
            console.log(type);
        } else { 
            file.style.display = "block";
            console.log(type);
            }
        }

******************************最终编辑******************** **** 保留原始代码,但添加了内联 CSS。

<div class="form-group col-md-6" id="doclicense" style="display:none;">

现在完美运行。

标签: javascripthtml

解决方案


下面是如何编写此代码的示例(即使仍然存在恐怖)

// declare them here and not in a function where they will be redone each time the function is called

const
  file_IHM  = document.querySelector('#doclicense')
  ,
  type_IHM  = document.querySelector('#accountType')  // and not with .value ...!
;


type_IHM.onchange = function()
{
  file_IHM.style.display = (this.value==='doctor')?"block":"none"; 

  console.log('type_IHM.value',  this.value );

}
#doclicense { display : none; } 
<div>
  <select id="accountType" name="type" class="form-control" >  <!--  let the js in the js part -->
    <option required>Account Type</option>
    <option value="doctor"  id="doctor"  >Doctor</option>
    <option value="regular" id="regular" >Regular Account</option>
  </select>
</div>

<div class="file-class" id="doclicense">  <!--  do not use class="hidden... -->
  <input type="file" name="license" />
  <input type="submit" />   <!-- there is no form anywhere...   why don't you use <button> ?? -->
</div>


推荐阅读