简体   繁体   中英

How to append value from ajax to select option?

How to bind the value from the ajax call to the select option? This is an example of my API https://codepen.io/anon/pen/wNrLZm?editors=1010 I fetched data and need to print in HTML select option? Look my code

 <div class="row">
  <select class="form-control" name="result" id="result">
    <option value="1">1</option>
  </select>
</div>

<script type="text/javascript">
  $.ajax({
    url: 'index.php?route=api/reifenmontage/get_marka_data',
    context: document.body,
    success: function(data) {
      let resultElement = []
      resultElement = document.getElementById("result");
      resultElement.innerHTML = data;
    }
  });
</script>

The issue here is that you are returning JSON from the api and appending it into your HTML code.

There are many ways to achieve this. You could do something like this below. The basic idea is to loop through your array and generate an options tag with the iterated value and then append to your DOM.

$.each(data, function(index) {
    $('#result').append($('<option>', { value : data[index].value}).text(data[index].label));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM