根据选择更改创建动态表单元素

时间:2020-02-26 21:33:31

标签: jquery asp.net-core

有一个要求根据用户从选择字段中的选项列表中进行选择来提示用户一组(可配置)输入(主要是文本框)的要求。我不想定义所有输入,然后显示/隐藏不同的组,而是根据用户选择将这些组件注入UI。我认为我还没有看到类似的东西,而没有提前定义所有输入元素。

我正在考虑将输入的定义保留在json或模型类中。

换句话说,类似于此用户界面,但是基于用户对“选择文件类型”的选择,它们可能会显示5个输入,或者只有4个或3个输入。

除了使用jQuery根据用户选择显示/隐藏不同的输入组外,还可以通过其他方式实现这种“动态”形式吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为最好的解决方案是将所有五个输入添加到UI中,并使用CSS类隐藏/显示最后2个输入(因为始终需要3个,因此始终显示),具体取决于用户的从选项列表中选择。

<label>Please select an option</label>
<select id="choice">
  <option value="3">3 Inputs</option>
  <option value="4">4 Inputs</option>
  <option value="5">5 Inputs</option>    
</select>
<button id="btn">Go</button>
<br>    
<div id="container" class="container">
  <div>
    <label for="input-001">Input 001</label>
    <input type="text" id="input-001" name="input-001">
  </div>
  <div>
    <label for="input-002">Input 002</label>
    <input type="password" id="input-002" name="input-002">
  </div>
  <div>
    <label for="input-003">Input 003</label>
    <input type="date" id="input-003" name="input-003">
  </div>
  <div id="div-004">
    <label for="input-004">Input 004</label>
    <input type="email" id="input-004" name="input-004">
  </div>
  <div id="div-005">
    <label for="input-005">Input 005</label>
    <input type="file" name="input-005">
  </div>  
</div>

添加 css 类:

.optional {
  display: none;
  /*visibility: hidden;*/ /*you may/nedd to use visibility instead of display*/
} 

将事件处理程序添加到按钮:

$(document).ready(function() {
    $("#btn" ).click(function(){
      let choice = $("#choice").val();
      if (choice == 3) {
        console.log("hide input-004 & input-005 ");
        $("#div-004").addClass("optional");
        $("#div-005").addClass("optional");
      } else if(choice == 4) {
        console.log("hide input-005 & display input-004 ");
        $("#div-004").removeClass("optional");
        $("#div-005").addClass("optional");
      } else if(choice == 5) {
        $("#div-004").removeClass("optional");
        $("#div-005").removeClass("optional");
      }
    })
})

这里是working fiddle example

相关问题