0

I want to show dynamic select option.

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

This select option will store value in the same table name "tenant". But if use name="tenant" in two div, it's not storing the right value. So I think, if the options show dynamically then it should work. But how can I do that? Is there another solution?

1 Answers1

1

I might do it like this instead, setting an array based on the selected button, and then populating the select element with that array, making sure to clear the select element each time.

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>
H H
  • 101
  • 3