1

I am trying to populate a select box based on JSON data returned from my ASP page: http://accdbmgr-001-site1.etempurl.com/ajax.asp

This is the data returned from the Server:

{
  "data": [{
    "Lastname": "Roussel",
    "Firstname": "Donald"
  }, {
    "Lastname": "Sabourin",
    "Firstname": "Manon"
  }, {
    "Lastname": "Kelly",
    "Firstname": "Bruce"
  }]
}

However, for some reason it just doesn't seem to be able to add my JSON data into the select box. I'd like for the options to appear as: Lastname, FirstName

<div id="test"></div>
<form>
  <select id="select1"></select>
</form>
$(document).ready(function() {
  $.get('http://accdbmgr-001-site1.etempurl.com/ajax.asp', {
    category: 'client',
    type: 'premium'
  }, function(data) {
    alert("success")
    //$("#test").html(data)
    var obj = JSON.parse(data);
    for (i in obj) {
      $('#select1').append(new Option(obj[i].Firstname, obj[i].Lastname));
    }
  });
});
2
  • Try for (i in obj.data) Commented Nov 7, 2019 at 15:49
  • first like @phuzi said you need to travel through obj.data instead of object, and then you need to build a string to pass to new option like this ${obj[i].Firstname}, ${obj[i].Lastname} because the first one is the display one and the second one is the value behind, so they will not appear both as you expect. Commented Nov 7, 2019 at 15:53

1 Answer 1

1

The main issue is because you're looping through obj, when you instead need to loop through the obj.data array.

Also note that you can use map() to build an array of strings which you can then append() once to make the logic more succinct and more performant.

Finally your code is currently creating an option element with Firstname as the text of the element, and Lastname as the value. If you want the text to be in Lastname, Firstname format you need to set the text to that explicitly. Try this:

var obj = {
  "data": [{
    "Lastname": "Roussel",
    "Firstname": "Donald"
  }, {
    "Lastname": "Sabourin",
    "Firstname": "Manon"
  }, {
    "Lastname": "Kelly",
    "Firstname": "Bruce"
  }]
}

var options = obj.data.map(function(item) {
  return `<option>${item.Lastname}, ${item.Firstname}</option>`;
});
$('#select1').append(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>
<form>
  <select id="select1"></select>
</form>

Also note that JSON.parse() is not needed if you set dataType: 'json' on the request, or use $.getJSON()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.