jQuery – 如何根据选定的下拉菜单显示/隐藏文本框

对不起,如果这是非常明显的,但我已经查找并寻找解决方案,但没有找到任何东西。 我对jQuery很新,所以即使找我想做的事情也很难。

我有一个页面,其中包含从数据库填充的一堆字段和下拉框。 因此,每个下拉列表都会在页面加载时选择正确的项目(存储在数据库中的项目)。 当该选项为“其他”时,我希望我的“其他”文本框显示出来。

所以,问题是; 如何在页面加载时根据选定的下拉项显示/隐藏该文本框? 我在研究中找到的所有东西都与下拉菜单的变化有关。 这适用于我拥有的其他页面之一。 我不想重新选择“其他”(触发更改事件)。

谢谢

$(function() { if($("#yourDropDown").val() == 0) //I'm supposing the "Other" option value is 0. $("#yourTextBox").hide(); }); 
 $("option").bind('click', function(){ var selected = $(this).val(); alert(selected+' selected'); if (selected == '1') { /* do anything you want */ } if (selected == '2') { /* do anything you want */ } //etc ... }); 

我必须做这件事。 这是我使用的代码:

 $(function() { var jqDdl = $('#ddl'), onChange = function(event) { if ($(this).val() === 'Other') { $('#otherTxtbox').show(); $('#otherTxtbox').focus().select(); } else { $('#otherTxtbox').hide(); } }; onChange.apply(jqDdl.get(0)); // To show/hide the Other textbox initially jqDdl.change(onChange); }); 

如果你有一个选择框,即

  

你可以绑定到.change() ,即

 $('.myselect').change(function() { --> do show hide here. }); 

查找jquery .show().show() .hide() 。 (http://api.jquery.com/show和http://api.jquery.com/hide )。

假设默认情况下你的html有两个框,隐藏了“其他”框。

 val = $('#myselect').val(); switch( val ) { case "Other": $('#mybox').hide(); $('#myotherbox').show(); break; } 

请尝试此代码,希望它可以工作

   $(function() { $("#ddlEntity").change(function() { var selectedVal = $('option:selected', this).text(); if(selectedVal == "Other") { $('#txtOtherEntity').css('display', 'block'); } else { $('#txtOtherEntity').css('display', 'none'); } });