error with document.getElementById() - javascript

I am trying to write a jdo query in which I have to get a set of values based on the category that the user selects on the jsp...my query looks like this
Query query2 = pm.newQuery("select from " + ProductDB.class.getName()+ "where pCategory = " document.getElementById("cname").text);
Now on my jsp page, I have a dynamic drop-down box and in the tag I have given the id tag as "cname". So when I execute the above query I am hoping it will get the category that the user selects.
However I am getting this error:
Syntax error on token "document", delete this token
My select tag looks like this :
<select name = "cname" id="cname">
.
.
.
</select>
What am i missing here?
UPDATE :
I am putting my entire code for the jsp file below :
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<%# page import="java.util.*"%>
<%# page import="javax.jdo.Query"%>
<%# page import="javax.jdo.PersistenceManager"%>
<%# page import="com.google.appengine.api.users.User"%>
<%# page import="com.google.appengine.api.datastore.Key"%>
<%# page import="com.google.appengine.api.users.UserService"%>
<%# page import="com.google.appengine.api.users.UserServiceFactory"%>
<%# page import="java.net.*"%>
<%# page import="javax.servlet.http.HttpServletRequest"%>
<%# page import="com.nerdy.needs.*"%>
<html>
<head>
<title>Product Inventory</title>
<META HTTP-EQUIV="Refresh" CONTENT="450">
<link rel="stylesheet" href="login.css" type="text/css" />
</head>
<h1 align="center">Product Inventory</h1>
<body>
<form>
<table>
<tr>
<td>View</td>
<td><select name="cname" id="cname">
<option value="all">All</option>
<%
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery("select cname from "
+ CategoryDB.class.getName());
List<String> categories = new ArrayList<String>();
categories = (List<String>) query.execute();
String[] c = categories.toArray(new String[categories.size()]);
for (int i = 0; i < c.length; i++) {
String s = c[i];
%>
<option value="<%=s%>"><%=s%></option>
<%
}
%>
</select></td>
<td>Products</td>
</tr>
</table>
</form>
<%
if (document.getElementById("cname").value == "all") {
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery("select * from "
+ ProductDB.class.getName());
List<ProductDB> prods1 = (List<ProductDB>) query1.execute();
if (prods1.isEmpty()) {
%>
<table class="items">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<tr class="lightBlue">
<td class="actions" colspan=100%>
<p>No items were found.</p>
</td>
</tr>
</table>
<%
} else {
%>
<table class="topics">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<%
for (ProductDB p : prods1) {
%>
<tr>
<td>
<p><b> <img width="100" height="100"
src="http://localhost:8888/serve?id= <%=p.getProductImage()%>">
</b></p>
</td>
<td>
<p><b><%=p.getProductCategory()%></b></p>
</td>
<td>
<p><b><%=p.getProductName()%></b></p>
</td>
<td>
<p><b><%=p.getProductPrice()%></b></p>
</td>
<td>
<p><b><%=p.getProductDescription()%></b></p>
</td>
</tr>
<%
}
%>
</table>
<%
pm1.close();
}
} else {
PersistenceManager pm2 = PMF.get().getPersistenceManager();
Query query2 = pm.newQuery("select * from "
+ ProductDB.class.getName() + "where pCategory = "
+ document.getElementById("cname").value);
List<ProductDB> prods2 = (List<ProductDB>) query2.execute();
if (prods2.isEmpty()) {
%>
<table class="items">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<tr class="lightBlue">
<td class="actions" colspan=100%>
<p>No items were found.</p>
</td>
</tr>
</table>
<%
} else {
%>
<table class="topics">
<tr>
<th class="main">Image</th>
<th class="main">Category</th>
<th class="main">Name</th>
<th class="main">Price</th>
<th class="main">Description</th>
</tr>
<%
for (ProductDB p : prods2) {
%>
<tr>
<td>
<p><b> <img width="100" height="100"
src="http://localhost:8888/serve?id= %=p.getProductImage()%>">
</b></p>
</td>
<td>
<p><b><%=p.getProductCategory()%></b></p>
</td>
<td>
<p><b><%=p.getProductName()%></b></p>
</td>
<td>
<p><b><%=p.getProductPrice()%></b></p>
</td>
<td>
<p><b><%=p.getProductDescription()%></b></p>
</td>
</tr>
<%
}
%>
</table>
<%
pm2.close();
}
}
%>
</body>
</html>
I am getting "document cannot be resolved" errors in two places - one at the if statement
if(document.getElementById("cname").value=="all")
and the other at the query statement
Query query2 = pm.newQuery("select * from " + ProductDB.class.getName()+ "where pCategory = " + document.getElementById("cname").value);
Can anyone help me to figure out what is wrong?

Your concrete problem is that you're mixing Java/JSP with JavaScript. You seem to expect that they run in sync and you seem to expect that JavaScript's document object variable is also present in JSP scriptlet code.
This is wrong. Java/JSP is a HTML code generator. It runs in webserver upon a HTTP request and generates HTML/JS code and sends it back to webbrowser as HTTP response. All the webbrowser retrieves is plain HTML/JS code. Rightclick the page in webbrowser and do View Source to see it yourself.
Your concrete functional requirement seems to be that you need to grab the the submitted value of
<select name="cname">
in the Java/JSP side.
You need to get it as a request parameter by HttpServletRequest#getParameter(). So, replace
<%
if (document.getElementById("cname").value == "all") {
// ...
}
%>
by
<%
if ("all".equals(request.getParameter("cname"))) {
// ...
}
%>
That said, writing Java code in JSP files is a poor practice. Work on that as well. Note that this problem is unrelated to JDO.

You forgot the plus mark before the document.getElementById.
The correct code would be
Query query2 = pm.newQuery("select from " + ProductDB.class.getName() + "where pCategory = " + document.getElementById("cname").text);
Also, although that will fix the syntax error, the code still won't work. According to W3C DOM specification, the <select/> element doesn't have the text attribute; you should use the value, or selectedIndex in conjunction with options instead.

Try this way:-
var i = document.getElementById("cname").selectedIndex;
document.getElementById("cname").options[i].text;
OR
document.getElementById("cname").value
UPDATE:
Column names are missing too. It should be either * or specific column names.
Query query2 = pm.newQuery("select * from " + ProductDB.class.getName()+ "where pCategory = " + document.getElementById("cname").value);
As per your error update
your code should be as follows:-
if(document.getElementById("cname").value=="all")
{
<%
PersistenceManager pm1 = PMF.get().getPersistenceManager();
Query query1 = pm1.newQuery("select * from " + ProductDB.class.getName());
List<ProductDB> prods1 = (List<ProductDB>) query1.execute();
%>
}
JSP tags should be declared between tags <% and %> and other html tags should be outside.
As per your Code:
The problem is document.getElementById("cname").value calling inside the JSP tags. That is wrong.
Here either you can pass cname value as query string and get value through the parameter
OR
Assign document.getElementById("cname").value value to JSP variable and process it.

Related

How to set number of <td> tag dynamically where number of <td> tag is fixed?

I have a table looks like below:
<table border="1">
<tr bgcolor=#0D9381>
<th rowspan=2><center>Characteristics</center></th>
<th rowspan=2><center>Spec.</center></th>
<th colspan=<%=gcaqa.getX2() %>><center>Observed<br>Value</center></th>
<th rowspan=2><center>Date of<br>Analysis</center></th>
</tr>
<%
if(vaqm!=null && vaqm.size()>0){
for(class_div h11:vaqm){
%>
<tr bgcolor=#02321D>
<td><center><%=h11.getCharacteristics() %></center></td>
<td><center><%=h11.getSpec() %></center></td>
<td><center><%=h11.getObservedValue1() %></center></td>
<td><center><%=h11.getObservedValue2() %></center></td>
<td><center><%=h11.getObservedValue3() %></center></td>
<td><center><%=h11.getDateofAnalysis() %></center></td>
</tr>
<%
}
}
%>
</table>
But here I want to show only <%=gcaqa.getX2() %> number of Observed Value out of <%=h11.getObservedValue1() %>, <%=h11.getObservedValue2() %> and <%=h11.getObservedValue3() %>
that is out of 3rd, 4th and 5th td tag I want to display only <%=gcaqa.getX2() %> number of td tag.
I made it sure that number of observed value is less than or equals to <%=gcaqa.getX2() %>.
Please someone give any clue. Because there is no clue in the internet. In my case <%=gcaqa.getX2() %> is 2. So, to be very clear. I want to show only two td tag containing observed value out of 3.

how to get the value of the button by clicking that was created dynamically using loop

i created a html button in jsp using while loop i want to get the value of the specific button that was clicked but it shown result as undefined.
i don't no what to do and also don't no is it possible or not i am new to java Script.
Please help me thanks in advance.
Blockquote
this is what i tried but its not working giving the resut as undefined
<td><button value="<%= path%>" onclick="myFunction()"><%= path %></button></td>
<script>
function myFunction() {
alert(this.value);
<% session.setAttribute("gurufile",path );%>
}
</script>
Blockquote
this is my whole code i fetch the value of the button from the database
<%#page import="java.util.ArrayList"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.ResultSet"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
out.println(request.getParameter("roll_no"));
%>
<h3 align="center" style="color:BROWN;"> Dr.A.P.J. Abdul Kalam Technical University, Uttar Pradesh, Lucknow</h3>
<h4 align="center" >( Formerly Uttar Pradesh Technical University )</h4>
<h4 align="center" style="color:blue;">AKTU-OneView</h4>
</br>
<hr align="center" style="color:lightgrey;">
<h3>Student Result</h3>
<%!
//golbally declear
String class_name=null;
String branch=null;
String rollno =null;
String path =null;
ArrayList a = new ArrayList();
int count =0;
%>
<%
//String roll_no = "1634010009";
String roll_no = request.getParameter("roll_no");
String url="jdbc:mysql://localhost/student_result";
String username="root";
String password="bilalminto";
String query="select * from new_student where roll_no='"+roll_no+"'";
System.out.println("rollno "+roll_no);
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection(url, username, password);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
String student_name=null;
//String class_name=null;
//String branch=null;
//String rollno =null;
String father_name = null;
String mother_name = null;
if(rs.next()){
student_name=rs.getString("student_name");
class_name=rs.getString("class");
branch=rs.getString("branch");
rollno=rs.getString("roll_no");
father_name=rs.getString("fathers_name");
mother_name=rs.getString("mothers_name");
}
//Statement stm=con.createStatement();
//ResultSet rst=stm.executeQuery(query);
%>
<hr align="center" style="color:lightgrey;"></br>
<table width=100% border=1 cellspacing="0">
<tr align="left">
<td><b>Institute Code & Name :</b></td>
<td colspan="5"> (340) VIVEKANANDA COLLEGE OF TECHNOLOGY & MANAGEMENT, ALIGARH</td>
<td rowspan="5">print view</td>
</tr>
<tr>
<td><b>Course Code & Name:</b></td>
<td colspan="2"><%=class_name%></td>
<td ><b>Branch Code & Name</b></td>
<td colspan="2"><%=branch%></td>
<%
System.out.println("branch "+branch);
%>
</tr>
<tr>
<td><b>Roll No:</b></td>
<td colspan="2"><%=roll_no %></td>
<td><b>Enrollment No</b></td>
<td colspan="2">163401047822</td>
</tr>
<tr>
<td><b>Name:</b></td>
<td colspan="2"><%=student_name%></td>
<td><b>Mother Name</b></td>
<td> <%=mother_name%></td>
</tr>
<tr>
<td><b>Father's Name:</b></td>
<td colspan="2"><%=father_name%></td>
<td><b>Gender</b></td>
<td colspan="2">M</td>
</tr>
</table></br>
<%
}
catch(Exception e){
e.printStackTrace();
}
session.setAttribute("roll_no", roll_no);
%>
<hr align="center" style="color:lightgrey;">
<h3>One View Result</h3>
<hr align="center" style="color:lightgrey;">
<%
//String roll_no=session.getAttribute("roll_no").toString();
String query1 = "select distinct semester from subject where class_name='"+class_name+"' && branch='"+branch+"'";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection(url, username, password);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query1);
Statement st1 =con.createStatement();
ResultSet rs1 =null;
Statement st4 =con.createStatement();
ResultSet rs4 =null;
Statement st5 =con.createStatement();
ResultSet rs5 =null;
String semester =null;
String subject_code=null;
String subject_name=null;
String max_marks=null;
String marks_obtained = null;
//String path =null;
while(rs.next()){
semester=rs.getString("semester");
%>
<lable><b>Samester:</b></lable><label><%=semester%></label><lable><b>Total Subjects:</b></lable><label></label></br>
<lable><b>Total Marks:</b></lable><label>900</label><lable><b>Marks Obt:</b></lable><label>500</label></br>
</br>
<table width=100% border=1 cellspacing="0">
<tr>
<td><b>Code</b></td>
<td><b>Name</b></td>
<td><b>Max Marks</b></td>
<td><b>Marks Obtain</b></td>
<td><input type="text" name="" value="view copy"></td>
</tr>
<%
String query2 ="select * from subject where semester='"+semester+"'";
rs1=st1.executeQuery(query2);
while(rs1.next()){
subject_code=rs1.getString("subject_code");
subject_name=rs1.getString("subject_name");
max_marks=rs1.getString("max_marks");
String query3 ="select * from add_marks where roll_no='"+roll_no+"' and subject_code='"+subject_code+"'";
System.out.println(subject_code);
rs4 = st4.executeQuery(query3);
if(rs4.next() && rs4.getString("roll_no").equalsIgnoreCase(roll_no) && rs4.getString("subject_code").equalsIgnoreCase(subject_code)){
// if(rs4.next()){
marks_obtained=rs4.getString("marks_obtained");
path=rs4.getString("path");
}else{
marks_obtained = "Not Updated";
path = "Not Updated";
}
//session.setAttribute("gurufile",path );
a.add(count, path);
//out.println("pathof" +path);
%>
<tr>
<td><%=subject_code%></td>
<td><%=subject_name%></td>
<td><%=max_marks%></td>
<td><%=marks_obtained%></td>
<td><button value="<%= path%>" onclick="myFunction()"><%= path %></button></td>
</tr>
<%
count++;
}
%>
</table>
</br>
</br></br>
<%
}
%>
<%
}
catch(Exception e){
e.printStackTrace();
}
session.setAttribute("roll_no", roll_no);
%>
</body>
</html>
<script>
function myFunction() {
alert(this.value);
<% session.setAttribute("gurufile",path );%>
}
</script>
Blockquote or there is any other technique to get the the value of the button that was clicked
You need to pass the this reference to the function:
<button value="<%= path%>" onclick="myFunction(this)">
This way you get the clicked button as a parameter in the function:
function myFunction(button) {
alert(button.value);
}

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,

How to display parsed data from ajax in express.js

I have this page made using node.js + express where I am displaying the following table :
I wish to reload only the table with new data using ajax when limit is changed using the dropdown (one with the label show result), but am having trouble doing so.
Here's the ejs code that displays my table :
<table class="assignment-table table table-striped table-bordered table-hover table-condensed table-responsive">
<thead>
<tr>
<th>S.No.</th>
<th>Name</th>
<th>Subject</th>
<th>Topic</th>
<th>Faculty</th>
<th>Posted</th>
<th>Last Date</th>
<th>Mode of Submission</th>
</tr>
</thead>
<tbody class="table_body">
<% for(var i =0;i< result.length;i++) { %>
<tr>
<td class="result_id">
<a target="_blank" href="/assignment/abc.pdf" class="download-link" id="">
<%= result[i]._id %>
</a>
</td>
<td class="result_name">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].nameAssignment %>
</a>
</td>
<td class="result_subject">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Subject %>
</a>
</td>
<td class="result_topic">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Topic %>
</a>
</td>
<td class="result_faculty">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Faculty %></a>
</td>
<td class="result_posted">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Posted %></a>
</td>
<td class="result_lastdate">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].LastDate %></a>
</td>
<td class="result_submission">
<a target="_blank" href="/assignment/abc.pdf" class="download-link">
<%= result[i].Submission %></a>
</td>
</tr>
<% } %>
</tbody>
</table>
In the filter_result() route mentioned above, I am fetching limit from the url and querying the database with new limits and rendering the page again.
Router.get('/filter_result',(req,res) => {
limit = parseInt( decodeURIComponent(req.query.limit) );
models.filterResults(limit, (count,result) => {
//if (err) throw err;
console.log(limit);
//res.send(result);
res.render('assignment-list',{limit:limit,result:result,count : count});
});
});
How can I redisplay the table in the ejs page?
Basically your .ejs format is rendered only once when you load or reload the page. So what you do is re-render (or, replace) the HTML from your AJAX call on top of already-rendered HTML.
It seems that you're using jQuery already so my example code uses jQuery too.
Re-rendering (or, again, replacing) HTML depends on what your /filter_result responds. If it's just bunch of <tr>s then it might be
JS
$('table.assignment-table').find('tbody').html(result);
If it's the entire <table> then you'd better wrap <table> with some wrapper like <div> and do the following.
HTML
<div id="table-wrapper">
<table>
...
</table>
</div>
JS
$('div#table-wrapper').html(result);
How you refer your wrapper and replace the content can vary.
Update 1
Assuming your API (/filter_result) returns an array of assignment objects like
{
"status": "success",
"data": [
{
"Subject": "Your subject",
"Topic": "Your topic",
...
},
...
]
}
you can create bunch of <tr/>s from data and replace the existing <tr/>s with them like (with jQuery of course. About creating DOM with jQuery, you can refer the docs.)
$.ajax({
method: 'GET',
url: 'URL_TO_FILTER_RESULT',
data: SOME_DATA,
success: function(res) {
var assignments = res.data;
var body = [];
assignments.forEach(function(assignment) {
var tr = $('<tr/>');
tr.append($('<td/>').html('' + assignment.Subject + '');
tr.append($('<td/>').html('' + assignment.Topic + '');
...
body.push(tr);
});
$('table.assignment-table').find('tbody').html(body);
}
})

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