Using ejs input for js if statement - javascript

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.

Related

Displaying MySQL query results as HTML with EJS

I am building an app (using EJS view engine and Node.js) which interacts with an MySQL database I have built locally. I can receive results from my queries successfully as a JSON string, but I cannot send the information to a view (to be displayed as HTML) as I am getting the error: unsafefoods is not defined.
My 'app.js' file declares:
var unsafefoods = require('./routes/unsafefoods');
app.use('/unsafefoods', unsafefoods);
My route 'unsafefoods.js' declares:
var express = require('express');
var router = express.Router();
/* GET all safe foods */
router.get('/', function (req, res, next) {
connection.query('SELECT * from appycavy.foods WHERE safe = 0', function (error, rows, fields) {
if (error) {
res.send(JSON.stringify({
"status": 500,
"error": error,
"response": null
}));
//If there is error, we send the error in the error section with 500 status
} else {
res.render(unsafefoods, {
title: 'Unsafe foods list',
data: rows
})
}
});
});
module.exports = router;
And my view 'unsafefoods.ejs' declares:
<!DOCTYPE html>
<html lang="en">
<head>
<% include ./partials/head %>
</head>
<body class="container">
<header>
<% include ./partials/header %>
</header>
<main>
<div class="jumbotron">
<h2>Safe foods</h2>
<p>The following is a list of all
<b>unsafe</b> foods
</p>
<!-- table to display unsafe foods -->
<table width='80%' border=0>
<tr style='text-align:left; background-color:#CCC'>
<th>ID</th>
<th>Name</th>
<th>Safe</th>
<th>Type</th>
<th>Favourite</th>
<th>Water</th>
<th>Energy</th>
<th>Vitamin C</th>
<th>Sugar</th>
<th>Lipid fat</th>
<th>Calcium</th>
<th>Phosphorus</th>
<th>CaP ratio</th>
</tr>
<!--
Using FOREACH LOOP for the users array
myArray.forEach(function(el, index) {
// el - current element, i - index
});
-->
<% if (data) { %>
<% data.forEach(function(unsafefoods){ %>
<tr>
<td><%= unsafefoods.id %></td>
<td><%= unsafefoods.name %></td>
<td><%= unsafefoods.safe %></td>
<td><%= unsafefoods.type %></td>
<td><%= unsafefoods.favourite %></td>
<td><%= unsafefoods.water %></td>
<td><%= unsafefoods.energy %></td>
<td><%= unsafefoods.vitaminC %></td>
<td><%= unsafefoods.sugars %></td>
<td><%= unsafefoods.lipidFat %></td>
<td><%= unsafefoods.calcium %></td>
<td><%= unsafefoods.phosphorus %></td>
<td><%= unsafefoods.capRatio %></td>
<td>
<div style="float:left">
<a href='/unsafefoods/edit/<%= unsafefoods.id %>'>Edit</a>
<form method="post" action="/unsafefoods/delete/<%= unsafefoods.id %>" style="float:right">
<input type="submit" name="delete" value='Delete' onClick="return confirm('Are you sure you want to delete?')" />
<input type="hidden" name="_method" value="DELETE" />
</form>
</div>
</td>
</tr>
<% }) %>
<% } %>
</table>
</div>
</main>
<footer>
<% include ./partials/footer %>
</footer>
</body>
</html>
Any pointers would be appreciated,
Thanks,
unsafefoods variable is undefined in your unsafefoods.js file.
Your code should be
res.render('unsafefoods', {
title: 'Unsafe foods list',
data: rows
})
you are missing '' around unsafefoods.

Rails - Table <TR> - Add filter with a button / Jquery

I would like to implement a filter on my table by clicking on a button
I got a table here :
<div class="table-container">
<table class="table table-filter">
<tbody>
<% if current_user %>
<% #book.each do |book| %>
<tr data-status = "###">
<!-- I would like to implement <%= book.style %> inside that data-status, to filter on the type of books -->
<td><%= book.name %></td>
<td> <%= book.author %></td>
</tr>
</tbody>
<% end %>
<% end %>
</table>
</div>
And a Script to filter when i click on the button
<button type="button" class="btn btn-success btn-filter" data-target="novel">PC</button>
Here is the script :
<script>
$(document).ready(function () {
$('.btn-filter').on('click', function () {
var $target = $(this).data('target');
if ($target != 'all') {
$('.table tr').css('display', 'none');
$('.table tr[data-status="' + $target + '"]').fadeIn('slow');
} else {
$('.table tr').css('display', 'none').fadeIn('slow');
}
});
});
</script>
I dont know how to pass the value of the book type , inside the Data-status = <% book.style %> and even when i put a text value , like Novel , it doesnt filter on the table.
I dont really know where am I wrong and im looking for help on this. Do I need to use a content_tag ?
you can simply:
<tr data-status = "<%= book.style %>">

Passing current or updated text field tag value for update button?

I have a table in which I am loading values from the session.
I am working on the update button. I want to pass the current value of the text field to the controller to perform the update operation.
My code looks like this:
<table>
<thead>
<tr>
<th width="200">Name</th>
<th width="150">Price</th>
<th>Quantity</th>
<th width="150">Total</th>
<th></th>
</tr>
<% grand_total = 0 %>
<% session[:cart].each do |key, item| %>
<tr>
<td><%= item[:name] %></td>
<td>Rs. <%= item[:price] %></td>
<td><%= text_field_tag(:quantity, item[:quantity]) %>
<%= link_to("Update", {:action => "update", :id => item[:id], :quantity => item[:quantity]}) %>
</td>
<td><%= item[:total_cost] %></td>
<td>
<%= link_to("X", {:action => "delete", :id => item[:id]}) %>
</td>
</tr>
<% grand_total = grand_total + item[:total_cost] %>
<% end %>
</thead>
</table>
When I hover over the update button, the path shows "localhost:3000/cart?quantity=1" even though I change the value in the text field.
ERB templates are rendered by Rails on the server side, but this interaction is occurring on the client side, in the browser.
<%= ... %> is a fancy form of string interpolation, but you can still pretty much think of it the same way:
quantity = 1
message = "You have #{quantity} items"
quantity = 2
puts message # -> You have 1 items
You wouldn't really expect that to print You have 2 items, would you?
Your easiest option is to put some javascript in the onchange directive on the text input that will update the submit button, but you might also want to look into "data-binding" if you encounter this problem a lot.

How to make multiple tr function in JavaScript/Rails?

I am working with Rails, and using JavaScript as well. I am having trouble getting Javascript function for the multiple tr in my table. I am using bootstrap to display my modal and everything works fine for the first tr, but it doesn't function for the others:
<script type = "text/javascript">
$(function(){
$("#btn-show-modal").click(function(e){
$("#dialogue-example").modal('show');
});
$("#btn-close-modal").click(function(c){
$("#dialogue-example").modal('hide');
});
});
</script>
<table class="table table-striped">
<thead>
<tr>
<th>Brand</th>
<th>description</th>
<th>Rate</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<% #products.each do |product| %>
<tr id ="btn-show-modal">
<td><%= product.brand %></td>
<td><%= product.short_description %></td>
<td><%= product.rate_amount %></td>
<td><%= product.created_at %></td>
<% name = product.name %>
<% description = product.description %>
</tr>
</tbody>
<% end %>
</table>
#BenjaminGruenbaum wrote in a comment:
IDs are unique (and can be only used on one element), use classes instead.

Add new row dynamically with Javascript/JQuery/Rails 3

I am building a timesheet form that consists of a calendar which enables a user to select a specified date, and search for a project. I have this functionality working. What I basically have is this:
Once the user searches for their project and press the plus button, that specified project. Which in this instance is Asda the user would then click the plus icon which would create a new row and put it into the table 'task for project. How can you do this in Javascript/JQuery.
Sorry for asking what may be seen as such a basic question, but am still learning Javascript/JQuery.
I currently have the plus icon linked to project_project_tasks_path( project.id ). This is just temporary.
This is what I have so far:
<div class="left">
<table border="2" width="" id='projects' class='datatable'>
<thead>
<tr>
<th>Number &nbsp</th>
<th>Name</th>
<th></th>
</tr>
</thead>
<tbody>
<% #projects.each do |project| %>
<tr>
<td><%= project.project_number %></td>
<td><%= project.project_name %></td>
<td><%= link_to image_tag("icons/add.png"), project_project_tasks_path( project.id ), :remote => true %></td>
<!-- link_to image_tag("icons/add.png"), tasklist_path(project.id), :as => "tasklist" -->
</tr>
<%- end -%>
</tbody>
</table>
</div>
<div class="right">
<b>Recently Viewed</b>
<table>
<tr>
<th>Project No.</th>
<th>Project names</th>
<th>Project Leader</th>
<th></th>
</tr>
<tr>
<td>123</td>
<td>Test</td>
<td>1</td>
<td><%= link_to image_tag("icons/add.png") %></td>
</tr>
</table>
</div>
</fieldset>
<fieldset>
<b><center>Hours for Week commencing: <span id="startDate"><%= Date.today.beginning_of_week.strftime('%d/%m/%Y') %></span></center></b>
</fieldset>
<!-- Task list table -->
<div style="float: right; width: 300px; padding-left: 20px;">
<fieldset>
<b>Tasks for project</b>
<ul id="task_list">
</ul>
</fieldset>
</div>
<!-- Hours list table -->
<fieldset>
<table>
<tr>
<td>Leave</td>
<td><input class="dayinput" type="text" name="Leave"></td>
</t>
<tr>
<td>TOIL</td>
<td><input class="dayinput" type="text" name="TOIL"></td>
</tr>
<tr>
<td>Sick</td>
<td><input class="dayinput" type="text" name="Sick"></td>
</tr>
<tr>
<td>Total</td>
<td><input id="total" class="total_low" type="text" value="0" disabled="">
</tr>
</table>
</fieldset>
Edited:
I have created a task_list.js.erb which is as followed:
$('#task_list').html('');
<% #project.project_tasks.each do |task| %>
$('#task_list').append('<ul><%= task.task_name %>');
<% end %>
Project Controller
def index
# check if we've got a project id parameter
if( params[:project_id].nil? )
#project = nil
else
#project = Project.find(params[:project_id])
end
if #project.nil?
#project_tasks = ProjectTask.all
else
#project_tasks = Project.find(params[:project_id]).project_tasks
end
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #project_tasks }
format.js # index.js.erb
end
end
From the changes made, it outputs:
JQuery Ui autocomplete code:
$(function() {
function log(message) {
$( "<div/>" ).text( message ).prependTo("#log");
}
$("#tags").autocomplete({
source : function(request, response) {
$.ajax({
url : "/projectlist",
dataType : "json",
data : {
style : "full",
maxRows : 12,
term : request.term
},
success : function(data) {
var results = [];
$.each(data, function(i, item) {
var itemToAdd = {
value : item,
label : item
};
results.push(itemToAdd);
});
return response(results);
}
});
}
});
});
Adding to the DOM with jQuery is very simple with the append or prepend method.
$('element_to_add_to').append('the html to append');
$('element_to_add_to').prepend('the html to append');
Check out the empty method in the jQuery docs as well.
Also, you have some bad markup. The task_list <ul> has no <li>'s and the table in there has an extra </tr>.
Edit: From your updated post, it seems like you want to not only insert a row in a table, but also save the data to your database at the same time. In that case, you'll want to make an ajax call to a controller method which will save the data in your DB. Then add the updated row to the table if the call is successful.
$.ajax({
type: "POST",
url: "path to your route",
data: "the data to send to your controller",
success: function(data){
// here is where you process the return value from your controller method
// the data variable will hold the return value if the call is successful
// you can make your controller return the html to be inserted in your table
// and insert it from here or just return a status message and build and add
// the html manually here.
}
});

Categories

Resources