2017-08-12 117 views
0

有一个(希望)简单的问题,我希望根据以前的下拉选择选项自动显示输​​入框。基于下拉选择的HTML动态输入框

所有这一切都很新,所以任何帮助,非常感谢!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<legend><b>Did Cardio Session?</b></legend> 
 
     <p> 
 
      <select name = "cardio" id = "cardio"> 
 
      <option value = "No" selected>No</option> 
 
      <option value = "Yes">Yes</option> 
 
      </select> 
 

 
      <div id = "cardioyes" style = "display:none;"> 
 
      <label for="How Long?">How Long?</label> 
 
      <input type = "text" name = "duration" /> 
 
      </div> 
 
     </p> 
 

 
     <script> 
 
     $('#cardio').change(function(){ 
 
     selection = $(this).val(); 
 
     switch(selection) 
 
     { 
 
      //show the <div> or not 
 
      case 'Yes': 
 
       $('#cardioyes').show(); 
 
       break; 
 
       default: 
 
       $('#cardioyes').hide(); 
 
       break; 
 
     } 
 
     }); 
 
     </script>

+0

你确实有代码;有什么问题? –

+0

它的工作我猜,也许你想'输入'在页面加载时更新? – kukkuz

回答

0

可能出了错是

  1. 唯一的东西你不加载jQuery库
  2. 您尝试的元素出现在之前使用.change事件处理程序代码 - $(document).ready照顾到这一点。

除了这些,因为你可以看到你的代码工作:

$(document).ready(function() { 
 
    $('#cardio').change(function() { 
 
    selection = $(this).val(); 
 
    switch (selection) { 
 
     case 'Yes': 
 
     $('#cardioyes').show(); 
 
     break; 
 

 
     default: 
 
     $('#cardioyes').hide(); 
 
     break; 
 
    } 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<legend><b>Did Cardio Session?</b></legend> 
 
<p> 
 
    <select name="cardio" id="cardio"> 
 
    <option value = "No" selected>No</option> 
 
    <option value = "Yes">Yes</option> 
 
    </select> 
 

 
    <div id="cardioyes" style="display:none;"> 
 
    <label for="How Long?">How Long?</label> 
 
    <input type="text" name="duration" /> 
 
    </div> 
 
</p>

+0

谢谢!是的,添加库解决了问题: –