-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiltering_table.html
82 lines (76 loc) · 2.09 KB
/
filtering_table.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vanilla Javascript Tutorial</title>
</head>
<body>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<p>Getting data from an api</p>
Search <input id="query" type="text"/><br><br>
<table style="border: 1px solid #ccc;">
<thead>
<tr>
<td>User Name</td>
<td>Email</td>
<td>Website</td>
</tr>
</thead>
<tbody id="list">
</tbody>
</table>
</body>
<script>
const request = new Request('https://jsonplaceholder.typicode.com/users/');
var query = document.getElementById('query');
var el = document.getElementById('list');
var allUsers = null;
query.addEventListener('keypress',function(e){
searchTable(query.value.toLowerCase());
});
function loadData(){
fetch(request)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Something went wrong on api server!');
}
})
.then(response => {
console.log(response);
allUsers = response;
renderTable(response);
}).catch(error => {
console.error(error);
});
}
function searchTable(query){
var filteredUsers = allUsers.filter((u) => {
return u.name.toLowerCase().includes(query) || u.website.toLowerCase().includes(query)
});
if(query != "" && filteredUsers.length > 0){
renderTable(filteredUsers);
}else{
renderTable(allUsers);
}
}
function renderTable(users){
el.innerText = "";
users.forEach(user=>{
var layout = '<tr>';
layout += '<td>' + user.name + '</td>';
layout += '<td>' + user.email + '</td>';
layout += '<td>' + user.website + '</td>';
layout += '</tr>';
el.innerHTML += layout;
})
}
loadData();
</script>
</html>