显示选择选项取决于按钮选择

时间:2020-10-05 11:32:22

标签: javascript jquery

我要显示动态选择选项。

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

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

1 个答案:

答案 0 :(得分:1)

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

    const regex = /(\s+.*[\^°<>#*~!"§$%?®©¶]+.*\s+|\s+.*\s+.*[\^°<>#*~!"§$%?®©¶]+|[\^°<>#*~!"§$%?®©¶]+.*\s+.*\s+)/;
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);
    }
}

相关问题