HTML 表单字段根据从下拉列表中选择的选项显示/隐藏

HTML Form field show/hide as per option selected from dropdown

本文关键字:选择 选项 显示 隐藏 下拉列表 字段 表单 HTML      更新时间:2023-09-26

今天,我在开发网站的道路上遇到了另一个大问题。我有一个带有一些基本 CSS 的正常形式。现在我想以这种方式使用表单,默认情况下某些字段将被隐藏,相应的文本字段将根据从下拉列表中选择的菜单激活。我首先想到以其他方式做PHP,但这不适合我的要求。我想要一些代码,它可以在同一页面上运行而无需刷新。所以我需要一些JavaScriptjQueryAjax的工作。但我不擅长这种语言,所以我需要你的帮助。

在做了大量的谷歌搜索之后,我找到了一段对我有用的JavaScript代码。这 http://jsfiddle.net/ZxLU9/

但问题是它仅适用于网站上给出的两个选项。我试图添加id3.但是当我增加 id 时,代码不再有效。此外,尽管此代码使用的是tbody,但隐藏的表单设计完全被破坏了。我在这里分享我的完整代码。在代码中有一些PHP代码,忽略它,我现在不关心。只需用我的实际设计修复我这个问题.

您可以在此处访问完整代码:http://jsfiddle.net/QvJH6/2/

检查名为"额外"的字段。 。这就是我想放置该代码的地方。

使用 Jquery 更改事件。

 $('#select_box').change(function() {
   if($(this).val() == "somevalue"){
     if($(this).next('input').css("display") == "none"){
          $(this).next('label').show();
          $(this).next('input').show();
      //Code to hide any existing fields go here.
     }
   }
 });

如果你使一切保持一致,这应该有效。如果没有,那么您将不得不为每个选择框做一个,并指定要显示的字段

//将函数调用从

/

/onchange="display(this,'text','image');"

//自onchange="display(this,'text','image',invisible);"

并且还将 JavaScript 中的显示函数更改为

function display(obj,id1,id2,id3) {
           txt = obj.options[obj.selectedIndex].value;
           document.getElementById(id1).style.display = 'none';
           document.getElementById(id2).style.display = 'none';
           document.getElementById(id3).style.display = 'none';
           if ( txt.match(id1) ) {
              document.getElementById(id1).style.display = 'block';
           }
           if ( txt.match(id2) ) {
              document.getElementById(id2).style.display = 'block';
           }
           if ( txt.match(id3) ) {
              document.getElementById(id2).style.display = 'block';
           }

}