-1

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>
Alex Al
  • 156
  • 4
  • 17
  • either have your backend return options or loop over it and build option elements.... – epascarello Feb 06 '19 at 14:39
  • 1
    Please post a [minimal version](https://stackoverflow.com/help/mcve) of `data` **in the question**. Whatever is posted in the codepen is not a valid array – adiga Feb 06 '19 at 14:40
  • 1
    Possible duplicate of [how can I give an array as options to select element?](https://stackoverflow.com/questions/14473207/how-can-i-give-an-array-as-options-to-select-element) and [populate drop down list with array](https://stackoverflow.com/questions/9895082) – adiga Feb 06 '19 at 14:42

1 Answers1

0

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));
});
  • I new in jquery I try this but without success $.ajax({ url: 'index.php?route=api/reifenmontage/get_marka_data', context: document.body, success: function(data){ let resultElement = document.getElementById("result"); resultElement.innerHTML = data; console.log(data) $.each(data, function(index) { $('#result').append($(' – Alex Al Feb 06 '19 at 15:11
  • Where is my mistake? – Alex Al Feb 06 '19 at 15:43
  • remove this line from your code: let resultElement = document.getElementById("result"); resultElement.innerHTML = data; console.log(data) – Nikhil Thakral Feb 07 '19 at 16:00