Below I have the code for my HTML table that is created from an ajax request pulling SharePoint list items. In the screenshot it shows how it works and what it displays after the button is clicked. How do I get my table to load without having to click the button that way when I load the page it is already displayed?
Secondly, how can I get rid of the header rows when it pulls from the second list since the information data is pulled from lists with the same items. I would much rather have a column on the side showing which list the rows are from instead.
Any suggestions?
AFter edit
https://i.stack.imgur.com/IXEWn.png
<script src="/Scripts/jquery-3.3.1.min.js"></script>
<input type="button" id="btnClick" value="Get Employee Information" />
<div id="EmployeePanel">
<table id='employeeTab' style="width: 100%;" border="1 px">
<tr>
<td>
<div id="employees" style="width: 100%"></div>
</td>
</tr>
</table>
</div>
$(function() {
$("#btnClick").click(function() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree";
var fullUrl1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree";
$.ajax({
url: fullUrl,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
$.ajax({
url: fullUrl1,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' + '<td><strong>Age</strong></td>' + '<td><strong>Position</strong></td>' + '<td><strong>Office</strong></td>' + '<td><strong>Education</strong></td>' + '<td><strong>Degree</strong></td>' + '</tr></thead><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objItems[i].Title + '</td>';
tableContent += '<td>' + objItems[i].Age + '</td>';
tableContent += '<td>' + objItems[i].Position + '</td>';
tableContent += '<td>' + objItems[i].Office + '</td>';
tableContent += '<td>' + objItems[i].Education + '</td>';
tableContent += '<td>' + objItems[i].Degree + '</td>';
tableContent += '</tr>';
}
$('#employees').append(tableContent);
}
function onError(error) {
alert('Error');
}
});
});
3
Answers
Your JS code must be on window’s load listener, that means when the page gets loaded.
make table in your html
changes in js
and for on load
Create the table headers under table content, then append to the table.