【问题标题】:show select option depends on button select显示选择选项取决于按钮选择
【发布时间】:2021-01-20 06:28:42
【问题描述】:

我想显示动态选择选项。

<div id="residential" >
   <input type="radio" value="apartment" id="type_apartment" name="type"  >
   <label for="type_apartment" class="radio-inline"> Apartment/Flat </label>
   <input type="radio" value="bachelor" id="type_bachelor" name="type">
   <label for="type_bachelor" class="radio-inline"> Bechelor  </label>
</div>

<!-- this will show when apartment select -->
<div class="form-group " id="tenant-flat">
   <select id="tenant-type" class="form-control" name="tenant">
      <option value="">Anyone</option>
      <option  value="family">Family</option>
      <option value="bechelor" >Bechelor</option>
   </select>
</div>
<!-- this will show when bechelor is select -->
<div class="form-group " id="tenant">
   <select id="tenant-type" class="form-control" name="tenant">
      <option value="">Anyone</option>
      <option  value="student">Student</option>
      <option value="job_holder" >Job Holder</option>
   </select>
</div>

此选择选项将值存储在相同的表名“租户”中。但是如果在两个 div 中使用 name="tenant",它就不会存储正确的值。所以我认为,如果选项动态显示,那么它应该可以工作。但我该怎么做呢?还有其他解决方案吗?

【问题讨论】:

  • id 是唯一的。你不能复制它们。对于你想做的事情,你应该使用一些 js
  • 您能分享任何参考资料吗?
  • 见这里:stackoverflow.com/questions/5940963/…(但你可以使用 vanilla JS 来完成这个简单的任务)。

标签: javascript jquery


【解决方案1】:

我可能会这样做,根据选定的按钮设置一个数组,然后用该数组填充选择元素,确保每次都清除选择元素。

function radio_click() {
    // Get elements
    var select = document.getElementById("select-occupant");
    var apt = document.getElementById("type_apartment");
    // Reset options
    select.options.length = 0;

    // Set option array based on selected
    if (apt.checked == true) {
        var options = {
            ValueA : 'Anyone',
            ValueB : 'Family',
            ValueC : 'Bachelor'
        };

    } else {
        var options = {
            ValueA : 'Anyone',
            ValueB : 'Student',
            ValueC : 'Job Holder'
        };
    }

    // Set options in select
    for(index in options) {
        select.options[select.options.length] = new Option(options[index], index);
    }
}
<div id="residential" >
   <input type="radio" value="apartment" id="type_apartment" name="type" checked=true onclick="radio_click()">
   <label for="type_apartment" class="radio-inline"> Apartment/Flat </label>
   <input type="radio" value="bachelor" id="type_bachelor" name="type" onclick="radio_click()">
   <label for="type_bachelor" class="radio-inline"> Bechelor  </label>
</div>

<!-- this is the only one needed now -->
<div class="form-group ">
   <select class="form-control" name="tenant" id="select-occupant">
      <option value="">Anyone</option>
      <option  value="family">Family</option>
      <option value="bechelor" >Bechelor</option>
   </select>
</div>

【讨论】:

  • sn-p 可能很有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2021-12-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
相关资源
最近更新 更多