Displaying results on new line

Viewed 62

I have an ajax request below that successfully returns the results. The results return is like the below.

Results structure

enter image description here

This is the ajax request that returns the structure above. File

$.ajax({
          url: domain+$(this).val(),
          dataType: 'jsonp',
          success: function (results) {
             $("#suggesstion-box").show();
             $("#suggesstion-box").html(results);

             console.log(results);
          },
            
 });    
           

Now how do I make the results return in the #suggestion-box like like this way?

Internet Explorer 

Internet Speed Test

Internet

At the moment, it shows like this in my #suggestion box with the code above

Internet Explorer, Internet Speed Test,Internet
2 Answers

You can first split the result using comma, then join them using <br/> (if element is a div element) or \n (if element is an input element):

$("#suggesstion-box").html(results[1].split(',').join('<br/>'));

Demo:

var results = 'Internet Explorer, Internet Speed Test,Internet';
$("#suggesstion-box").html(results.split(',').join('<br/>'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="suggesstion-box"></div>

Not the shortest option nor the best, but another option is to use the array map function.

I created a separated function to handle:

  1. Create new html element (p)
  2. Append the item to the new element.

Inside my map method, for each item inside the array, I called my function and appended the returned result (an html element) to my div.

const myDiv = $( "#suggesstion-box" );

const createMyElement = (el) => {
  const newElement = document.createElement('p');
  newElement.innerHTML = `<p>${el}</p>`;
  return newElement;
};

$.ajax({
  url: domain+$(this).val(),
  dataType: 'jsonp',
  success: function (results) {
    $("#suggesstion-box").show();
    results[1].map(el => myDiv.appendChild(createMyElement(el)));

  },
Related