根据选择选项显示div

时间:2009-11-06 23:15:21

标签: javascript jquery select hide show

哦帮助,我已经尝试了一百万种不同的方法但它仍然不起作用:如果从选择/选项框中选择更新或最终,它应该显示其中包含输入字段的div。它只执行switch语句中默认显示的内容。当然,只有在做出选择后我才能确定它是否显示输入字段。

在头部......

$(document).ready(function(){  
$('#needfilenum').hide();  
var optionValue = $("#needtoshow").val();  

switch (optionValue)  
{  
case 'update':  
$("#needfilenum").show();
break;  

case 'final':  
$("#needfilenum").show();  
break;  
default:  
$("#needfilenum").hide();  
break;  
    }
});
//});

'<select id="needtoshow" >  
<option id="dfaut" value="0">Select Something</option>
<option id="update" value="update">Update</option>
<option id="final" value="final">Final</option>
<option id="allergy"value="allergy">Vegan</option>  
</select>
<div id="needfilenum"  style="background:#f00;">  
<input type="text" name="wharever"   />
</div>  

我可以更改开关上的默认设置,这似乎决定了它显示的内容 也尝试了

//  $("#needtoshow").change(function() {  

//      switch ($(this).val())

5 个答案:

答案 0 :(得分:4)

如果您希望在下拉列表更改时显示div并隐藏,则需要绑定到change事件,例如:

$(document).ready(function() {
  $('#needfilenum').hide();

  $('#needtoshow').bind('change', function() {
    var optionValue = $("#needtoshow").val();

    switch (optionValue)
    {
      case 'update':
      case 'final':
        $("#needfilenum").show();
        break;

      default:
        $("#needfilenum").hide();
        break;
    }
  });
});

在您的代码中,switch语句仅在首次加载页面时运行一次。

答案 1 :(得分:2)

您可能希望在选择框中绑定事件侦听器。 (change event) 所以你会有以下几点:

$("#oldfilenum").change(function() {
  var optionValue = $(this).val();
  switch (optionValue) { 
    case 'update': 
      $("#needfilenum").show(); 
      break; 
    case 'final ': 
      $("#needfilenum").show(); 
      break; 
    default: 
      $("#needfilenum").hide(); 
  } 
};

答案 2 :(得分:1)

尝试这样的事情:

var selectBox = $("#oldfilenum"), magicDiv = $("#needfilenum");
selectBox.bind("change", function() {
    var val = this.value;
    if (val === "update" || val === "final") {
        magicDiv.show();
    } else {
        magicDiv.hide();
    }
});

当然,您可以使用switch,或者使用[]可接受的值并执行it.indexOf(val) > -1或其他任何内容。

当Victor评论另一个答案时,change会在MSIE中blur触发,因此如果这是一个问题,您可能想要使用另一个event,可能mouseup

答案 3 :(得分:0)

您应该查看change()事件。将其附加到<select>,然后执行您的逻辑。

答案 4 :(得分:0)

您的检查功能只运行一次,而不是每次更改选择字段。您需要将onchange处理程序放入选择字段:

<select id="needtoshow" onchange="your_function_name_here()">
相关问题