ericMTR
ericMTR

Reputation: 211

Populating select field by given dictionary

I found an example which populates the select field by given html strings:

<script>
$(document).ready(function() {

    $("#shape").change(function() {
        var val = $(this).val();
        $("#size").html(options[val]);
    });

    var options = [
        "<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>",
        "<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>",
        "<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>"
    ];

});
</script>

Which works fine but how do I have to change the script to do the same with a given dictionary?

options = {
    'ipe': ['80', '100'],
    'hea': ['90', '110'],
}

Here a picture to illustrate: enter image description here

Here my html snippet:

<div class="panel panel-primary">
  <div class="panel-body">
    <table>

<tr>
  <td>{{ form.shape.label }}</td>
  <td>{{ form.shape(class="form-control field", id="shape") }}</td>
  <td>{{ widgets.errors(form.shape.errors) }}</td>
</tr>

<tr>
  <td>{{ form.size.label }}</td>
  <td>{{ form.size(class="form-control field", id="size") }}</td>
  <td>{{ widgets.errors(form.size.errors) }}</td>
</tr>

    </table>
  </div>
</div>

Upvotes: 0

Views: 1910

Answers (1)

guest271314
guest271314

Reputation: 1

Try utilizing Array.prototype.map() , Array.prottotype.join()

var options = {
  "ipe": ["80", "100"],
  "hea": ["90", "110"]
};

$("#shape").change(function() {
  var val = options[this.value];

  $("#size").html(function() {
    return val.map(function(el) {
      return $("<option>", {
        "name": el,
        "value": el,
        "html": el
      })[0].outerHTML
    }).join("");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<label>Shape:
  <select id="shape">
    <option>select an option</option>
    <option name="ipe" value="ipe">ipe</option>
    <option name="hea" value="hea">hea</option>
  </select>
</label>
<label>Size:
  <select id="size">
  </select>
</label>

Upvotes: 1

Related Questions