Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

javascript - show div depending on select option

Oh help, I've tried it a million different ways yet it still does not work: If you select update or final from a select/option box, it should show the div that has an input field in it. It only does what the default shows in the switch statement. Of course, it's only after a selection is made that I want it to determine whether it shows the input field or not.

in head section...

$(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>  

I can change the default on the switch and that seems to dictate what it shows also tried

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

//      switch ($(this).val())
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to have the div show and hide when the drop-down changes, you need to bind to the change event, for example:

$(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;
    }
  });
});

In your code, the switch statement runs only once when the page first loads.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...