Passing string to popup - javascript

I'm working with a JSP page and it's displaying a table of a storage objects that was fetched. I want to have a popup to another JSP page when the user clicks on the number that is showing the size of the storage object.
How do I pass the name of the specified storage item to the popup JSP window with Javascript (or any other technique), and then retrieve that name in the popup JSP and be able to use it in that page's code?
The scriptlet for-loop looks like this:
<% for(Storage s : someList){ %>
<tr>
<td> <%= s.getName() %> </td> <td> <%= s.getSize() %> </td>
</tr>
<% } %>

Pass it as request parameter.
E.g.
<td onclick="window.open('popup.jsp?name=<%= URLEncoder.encode(s.getName(), "UTF-8") %>', 'windowname')">
with in popup.jsp:
<%= request.getParameter("name") %>
Or, more cleanly, with JSTL and EL:
<c:forEach items="${someList}" var="s">
<c:url value="popup.jsp" var="popupUrl">
<c:param name="name" value="${s.name}" />
</c:url>
<tr>
<td>${s.name}</td><td onclick="window.open('${popupUrl}', 'windowname')">${s.size}</td>
</tr>
</c:forEach>
with in popup.jsp
${param.name}

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.

Javascript: Unrecognized expression due to rails code in class name?

$(".collapse.summary_row_<%= pin %>").each(function() {
var thisId = $(this).find('#pin').text();
var sumVal = parseFloat($(this).find('#price').text());
var $rowsToGroup = $(this).nextAll('tr').filter(function() {
return $(this).find('#pin').text() === thisId;
});
$rowsToGroup.each(function() {
sumVal += parseFloat($(this).find('#price').text());
$(this).remove();
});
$(this).find('#price').text(sumVal);
});
<tr class="clickable" data-toggle="collapse" id="summary_row_<%=pin%>" data-
target=".summary_row_<%= pin %>">
<td><i class="glyphicon glyphicon-plus"></i></td>
<td> <%= pin%> </td>
<td align="right"> <strong> <%= number_to_currency(amount, unit: "",
precision: 2) if amount %> </strong> </td>
</tr>
<tr id="child_row_<%=pin%>" class="collapse summary_row_<%= pin %>"
align="right" >
<td class="child_data_<%=pin%>"><strong>Year</strong></td>
<td><strong>Quarter</strong></td>
<td><strong>Amount</strong></td>
</tr>
<% if detail %>
<% detail.each do |key, value| %>
<tr id="child_row_<%=pin%>" class="collapse summary_row_<%= pin %>"
bgcolor="#fba993" align="right" >
<td class="child_data_<%=pin%>" id="pin"><%= value[0]%></td>
<td id="quart"><%= value[1]%></td>
<td id="price"><%= number_to_currency(value[2], unit: "", precision: 2) %>
</td>
</tr>
<% end %>
The code above is the Javascript code and the code below is the html/ruby code. I'm trying to make it so that when the .clickable tr class gets clicked, the function will do it's work, but it doesn't and I get this message instead:
Uncaught Error: Syntax error, unrecognized expression: .collapse.summary_row_<%= pin %>
I've noticed that the other functions in my JS files worked, but they do not have the ruby syntax inside their class names so I'm assuming that the ruby code has something to do with this error.
You're writing Rails Code inside JavaScript file, it will not work there, you have to write your rails code inside html.erb file or you can call that function inside <script> tag from html.erb file or you can use dynamic data attributes inside your html tags
If you want to use Ruby variable in your Javascript you should add erb extension to your JS file: my_file.js.erb.
Other option is to use directly my_file.coffee. Here you can change adapt your JS file JsToCoffee
Hope it helps,

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 call js for appropriate element

Can't how to deal with my problem: part of view are hidden, when page is loaded.
Here is this part:
<table>
<% #websites.each do |website| %>
<%if (current_user.id == website.user_id)%>
<tr>
<td> <%= link_to(image_tag("/images/caret-horizontal.png", id: "caret-horizontal"), '#') %> </td>
<td> <h4><%= website.name %></h4> </td>
</tr>
</table>
<table id="<%= website.id %>"> // or can be like this:
//I don't what variant is better
<table id="table-data" data-id="<%= website.id %>">>
<tr >
<td >
<%= website.url %>
</td>
</tr>
<tr>
<td >
<%= website.category %>
</td>
</tr>
<tr>
<td><%= website.language %></td>
</tr>
</table>
And I can get attributes in JavaScript like this(thanks to good people):
var yourWebsiteId = $("#table-data").attr("data-id");
How I can choose approriate element and show it? I should use getElementById or something like this, but I don't know exactly how to do it.
Please help me, if you can.
$("#table-data").show()
You can find information on this from here
$("#table-data") gets a reference to the part of the dom you are trying to access (# denotes id, . denotes class), once you have a reference you can then call any jquery operation you want on it

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