Render a table from a variable (EJS) - javascript

Im trying to render a table, my variable was extracted from mongodb. This is my attempt in index.ejs
what have I done wrong here?
<table>
<tr>
<th>HomeTeam</th>
</tr>
<% for (var i = 0; i < result.length; i++) { %>
<tr>
<td><%= result[i].hteam %> </td>
</tr>
<% }); %>
</table>
In the console I get syntax error.
Any help to compile this would be much helpful as it has taken me several weeks to reach this point in my project :)
frederik

You have unnecessary bracket in closing for.
I think it should be:
<table>
<tr>
<th>HomeTeam</th>
</tr>
<% for (var i = 0; i < result.length; i++) { %>
<tr>
<td><%= result[i].hteam %> </td>
</tr>
<% }; %>
</table>

Related

Using ejs input for js if statement

I have a code problem I need to do for a class. I have a database that has users, another table has the titles which the user has access to. I'm trying to make a page where they can edit a user and when they click the button the form fills automatically with the id, first name and last name fine.
Now I'm trying to show what access the user selected has access to at the moment. And what I thought would just be a simple if statement has turned into a headache, it seems I can't access the id variable inside the html code that I want to insert and when I try to put the if statement outside, it says errors with the http headers, like it is sending too many renders. How can I accomplish this?
So here the code works but it loads the tabs of all of the users but I would like to filter the results based on the id.
<tbody>
<% all_users_to_modify.forEach(function(row){ %>
<tr>
<td>
<button class="btn btn-primary m-b-0"
onClick="fillForm('<%= row.id %>','<%= row.f_name %>','<%= row.l_name %>');";
onclick="moneyCalc('<%= row.id %>')" >
<%= row.id %>
</button>
</td>
<td><%= row.f_name %></td>
<td><%= row.l_name %></td>
<td><%= row.email %></td>
<td><%= row.phone_number %></td>
</tr>
<% }); %>
</tbody>
<table class="table table-striped table-bordered nowrap">
<thead>
<tr>
<th>Acceso</th>
</tr>
</thead>
<tbody id="lastResult">
</tbody>
</table>
function moneyCalc(id) {
'use strict';
var id = document.getElementById('id').value;
if (id) {
var html_to_insert = `
<% list_of_all_users_tabs.forEach(function(row1){ %>
<tr>
<td><%= row1.tab_name %> </td>
</tr>
<% }); %>
`;
lastResult.innerHTML += html_to_insert;
}
}
Now this is what I would like to do, in each row of the list_of_all_users_tabs it has a column that is the user_id and the other column is tab_name. So I have had two ideas but neither seem to work.
First idea was to put a while loop to compare the user_id in the db and the input id however I get: Error [ERR_HTTP_HEADERS_SENT]:
function moneyCalc(id) {
'use strict';
var id = document.getElementById('id').value;
if (id) {
while(list_of_all_users_tabs.user_id == id) {
var html_to_insert = `
<% list_of_all_users_tabs.forEach(function(row1){ %>
<tr>
<td><%= row1.tab_name %> </td>
</tr>
<% }); %>
`;
lastResult.innerHTML += html_to_insert;
}
}
}
Second idea had an if statement in the html code however it says id not defined:
function moneyCalc(id) {
'use strict';
var id = document.getElementById('id').value;
if (id) {
var html_to_insert = `
<% list_of_all_users_tabs.forEach(function(row1){ %>
<% if(row1.id == id) { %>
<tr>
<td><%= row1.tab_name %> </td>
</tr>
<% } %>
<% }); %>
`;
lastResult.innerHTML += html_to_insert;
}
}
Wrap your javascript code into <script> tag.
<script>
//Your code goes here
</script>
You need to set you header status to 200 in your route file.
res.json({
success: 'updated',
status: 200
})
And write you JS code inside <script> </script> tags only.

Dynamic Button in ejs to fill a form-field

i am currently using NodeJS with ejs Templates an a mySQL Database.
I created an ejs which can print a table dynamically which represents a table in the Database:
The Code looks like this:
<% for(var i=0; i<info.length; i++) {%>
<tr>
<td><b><%= info[i].id %></b></td>
<td><%= sinfo[i].path %></td>
</tr>
<% } %>
This work fine.
Somewhere in the same ejs you can find form with an input field.
Looks like this:
<input type="text" name="id" placeholder="id input"required>
Now i want to create a button in every row of the table.
When pressing the button the id-entry out of the colum where the button is in should be filled into my Form-Field. So every row would have one button!
I can't find a way to accomplish this.
This should work:
<% for(var i=0; i<info.length; i++) {%>
<tr>
<td><b><%= info[i].id %></b></td>
<td><%= info[i].path %></td>
<td><input type="button" onclick="document.getElementById('myText').value='<%= info[i].id %>'" value="Click" /></td>
</tr>
<% } %>
Than set the id myText to your input text:
<input type="text" name="id" id="myText" placeholder="id input">
A cleaner solution is to create a function somewhere in your javascript code:
function onClick(id){
document.getElementById('myText').value=id;
}
And so your ejs code will be:
<% for(var i=0; i<info.length; i++) {%>
<tr>
<td><b><%= info[i].id %></b></td>
<td><%= info[i].path %></td>
<td><input type="button" onclick="onClick('<%= info[i].id %>')" value="Click" /></td>
</tr>
<% } %>

Table filter in html with Javascript does not work

My table filter in html with Javascript does not work. I'm trying to filter a table generated from a ruby on rails query. I want to filter the table by the fields in the first column, I have a code that I tried with a simple table and it works fine, but using the same function in the ruby on rails html table does not work. I think tr [i] .style.display = "none";It does not work, but I'm not sure. When I run the filter, the table is recharged but remains the same.
<table id = "myTable" class="table table-hover table-bordered">
<thead>
<tr align="justify-center">
<th>Pais</th>
<th>Jugador</th>
<th>Partido</th>
<th>Minuto</th>
<th>Tarjeta</th>
</tr>
</thead>
<tbody>
<tr align = "center">
<td> Alemania </td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<% #tarjetasAmarilla.each do |tarjAm| %>
<tr align="center">
<td><%= tarjAm.player.country.nombre %></td>
<td><%= tarjAm.player.nombre %> <%= tarjAm.player.apellido
%> </td>
<td><%= #calendarios[tarjAm.match.calendar.id-1]
[0].country.nombre %> - <%= #calendarios[tarjAm.match.calendar.id-1]
[1].country.nombre %></td>
<td><%= tarjAm.minuto %>'</td>
<td><span class ="fa fa-sticky-note" style="color:yellow">
</span></td>
</tr>
<% end %>
<% #tarjetasRojas.each do |tarjAm| %>
<tr align="center">
<td><%= tarjAm.player.country.nombre %></td>
<td><%= tarjAm.player.nombre %> <%=
tarjAm.player.apellido %> </td>
<td><%= #calendarios[tarjAm.match.calendar.id-1]
[0].country.nombre %> - <%= #calendarios[tarjAm.match.calendar.id-1]
[1].country.nombre %></td>
<td><%= tarjAm.minuto %>'</td>
<td><span class ="fa fa-sticky-note" style="color:red">
</span></td>
</tr>
<% end %>
</tbody>
</table>
Javascript
function myFunction(id) {
var input, filter, table, tr, td, i, j, visible;
input = document.getElementById(id);
filter = input.id.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 1; i < tr.length; i++) {
visible = false;
td = tr[i].getElementsByTagName("td");
if (td[0] && td[0].innerHTML.toUpperCase().indexOf(filter) > -1) {
visible = true;
}else {
visible = false;
}
if (visible === true) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}

Add .png img to td elements in a dynamically created table in index.ejs

I have just created a table with help from embedded javascript. with help from messerbill I have come up with this:
<table id="Table1">
<tr>
<th>Kickoff</th>
<th>Status</th>
<th>Country</th>
<th>League</th>
<th>HomeTeam</th>
<th>AwayTeam</th>
</tr>
<% for (var i = 0; i < result.length; i++) { %>
<% var fileName = result[i].country + ".png" %>
<tr>
<td><%= result[i].Kickoff %> </td>
<td><%= result[i].statustype %> </td>
<td><img src="images/flags/<%= fileName %>" alt="images/flags/NoFlag.png" style="width:25px;height:15px;"/> <%= result[i].country %></td>
<td><%= result[i].league %> </td>
<td><%= result[i].hteam %> </td>
<td><%= result[i].ateam %> </td>
</tr>
<% }; %>
This works., However I need some sort of error handler when no png file is found.
Messerbill suggested yesterday to do something like this:
<% var path = Directory.GetCurrentDirectory() + "\\" + flags + "\\" + fileName %>
but this returns errors. Any suggestions as to how I could get a error handler working.
I would be interested to have it return from public/images/flags/noimg.png when no png file is found on search word.
Any help would be much appreciated
Update:
As an option I thought maybe I would try to search for the icon in the node app like so, :
var fs = require('fs');
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
var imgfile = arr[i].country
if (fs.exists('../public/images/flags/' + imgfile + ".png") == true) {
//console.log('/public/images/flags/' + imgfile + ".png");
console.log('fs exists');
} else {
console.log('Not Found!');
}
}
but here I get some error as im not able to locate a single icon.
frederik :)
just add the image tag to your loop:
<% for (var i = 0; i < result.length; i++) { %>
<tr>
<td><%= result[i].Kickoff %> </td>
<td><%= result[i].statustype %> </td>
<td><%= result[i].country %> <img src="/public/images/<%= result[i].country %>.png" alt="img" /> </td>
<td><%= result[i].league %> </td>
<td><%= result[i].hteam %> </td>
<td><%= result[i].ateam %> </td>
</tr>
<% }; %>

Create dynamic table - 3 Columns by N-rows?

I have a JS object that I'd like to iterate through, creating a three column, N-row, table.
I could have anywhere from 1 to N entries, but always want it a 3colxNrow table.
So far, I can get a single column, N row table:
<% for (var person in contacts){ %>
<div>
<table>
<tbody>
<tr>
<td>
<h2><u><%= person; %></u></h2>
<p id="email"><%= contacts[person]["email"]; %></p>
<p id="phoneNumber"><%= contacts[person]["phone number"]; %></p>
</td>
<td>
<img src=<%= contacts[person]["image"] %> >
</td>
</tr>
</tbody>
</table>
</div>
<br>
<% } // for (var person in contacts) %>
I'm stuck on how to do this for rows. The above returns this. Note it's 7 rows all one column.
I know I need to somehow loop through and add three td within the tr, but can't quite get how.
...
<tbody>
<tr>
<% for (var person in contacts){ %>
<td>
<h2><u><%= person; %></u></h2>
<p id="email"><%= contacts[person]["email"]; %></p>
<p id="phoneNumber"><%= contacts[person]["phone number"]; %></p>
</td>
<td>
<img src=<%= contacts[person]["image"] %> >
</td>
<% } // for (var person in contacts) %>
</tr>
</tbody>
...
This results in a single row, N columns wide. Do I need some logic, like for (var i = 1; i < 4; i++){ ??? } somewhere?
I thing, that for create some rows with 3 column, you can try insert for to before tr
rebuild your contacts arr:
let arrContacts = [];
let j = -1, i = 0;
for(let p in contacts ){
if(i%3===0){
arrContacts.push([]);
j++;
}
arrContacts[j].push(contacts[p]);
i++;
}
and use next template:
<tbody>
<% for (var i=0;i<arrContacts.length; i++){ contacts =arrContacts[i] ;%>
<tr>
<% for (var person in contacts){ %>
<td>
<h2><u><%= person; %></u></h2>
<p id="email"><%= contacts[person]["email"]; %></p>
<p id="phoneNumber"><%= contacts[person]["phone number"]; %></p>
</td>
<td>
<img src=<%= contacts[person]["image"] %> >
</td>
<% } %>
</tr>
<% } %>
</tbody>
After writing a 3 column, 4 row HTML table manually, physically printing the HTML out and taking a pen to it...I think I got it!
<div>
<table>
<tbody>
<% var i = 1; %>
<% var numCols = 3; %>
<tr>
<% for (var person in contacts){ %>
<% console.log("Person: " + person);%>
<td>
<h2><u><%= person; %></u></h2>
<p id="email"><%= contacts[person]["email"]; %></p>
<p id="phoneNumber"><%= contacts[person]["phone number"]; %></p>
</td>
<td>
<img src=<%= contacts[person]["image"] %> >
</td>
<% if (i%(numCols)===0 && i > 1){%>
</tr>
<tr>
<% } // (i%(numCols)===0 && i > 1) %>
<%i+=1;%>
<% } // for (var person in contacts) %>
</tr>
</tbody>
</table>
</div>
Yay! I think the trick was figuring out the conditional inclusion of <tr></tr> to end a row only when we hit our column limit.
(If someone comes across this and has any comments, improvements, warnings, please let me know!)

Categories

Resources