KrakenNeedsHelp KrakenNeedsHelp - 1 month ago 9
Javascript Question

jQuery AJAX - Returning and displaying multiple results

index.html

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="scripts.js"></script>
</head>
<body>
<h1>Order Request Form</h1>
<form id="create-form">
<table>
<tr>
<td>ID</td>
<td><input type="text" id="txtID"></td>
<td><button id="getid-button">GET Order by ID</button></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" id="txtName"></td>
<td><button id="getname-button">GET Order by Name</button></td>
</tr>
</table>
</form>
<div id="resultDiv"></div>
</body>
</html>




scripts.js

$(document).ready(function() {
var resultElement = $('resultDiv');
$('#getname-button').on('click',function(e) {
var searchName = $('#txtName').val();
e.preventDefault();
$.ajax ({
url: 'https://localhost:8080',
contentType: 'application/json',
}).then(function(response) {
for (var i = 0; i < response.length, i++) {
if (response[i].names.indexOf(searchName) > -1) {
resultElement.html('ID: ' + response[i].id + '</br>
+ 'Name: ' + response[i].name + '</br>');
}
}
});
});
});




So what I want to do is that whenever I press the "GET Order by Name" button, I want to return and display ALL the results with the name in it. Right now though, it is simply going through my JSON array and printing out the latest result found. Any idea how I might go about solving my problem? Thanks in advance.

Answer

You are using .html() witch will override all previous results use .append() instead.

var resultElement = $('#resultDiv'); //use # for ids

resultElement.append('ID: ' + response[i].id + '</br>
                         + 'Name: ' + response[i].name + '</br>')
//use append or else you will only see 1 result
Comments