I'm trying to get row values from a bootstrap table to send them to another JSP document while using jQuery, however seems like I can't find a proper way to do that.
<table class="table table-hover">
<thead>
<%
int serial = 0;
int id = 0;
String name = null;
double ammount = 0;
String date = null;
User user = null;
%>
<tr>
<th><%="Serial"%></th>
<th><%="Cost ID"%></th>
<th><%="Cost Name"%></th>
<th><%="Cost Ammount"%></th>
<th><%="Cost Date"%></th>
</tr>
</thead>
<tbody>
<%
try {
int id_id = (int) session.getAttribute("id");
List<Object[]> costs = scm.viewAll(sum.getUser(id_id));
for (Object[] cost : costs) {
id = (int) cost[0];
name = (String) cost[1];
ammount = (double) cost[2];
date = (String) cost[3];
serial += 1;
%>
<tr class="clickable-row" data-href="updatesingle">
<td><%=serial%></td>
<td><%=id%></td>
<td><%=name%></td>
<td><%=ammount%></td>
<td><%=date%></td>
</tr>
<%
}
} catch (Exception e) {
response.sendRedirect("home");
}
%>
This code above is the table code. As you can see the rows are clickable and I'm redirecting to a new page(JSP) when a row clicked, using jQuery:
jQuery(document).ready(function($) {
$(".clickable-row").click(function() {
window.document.location = $(this).data("href");
});
});
What I'm trying to do, is to pass for example the Cost ID(id variable) value to the next JSP page and manipulate it in some way, and the value should be of the specific row I clicked on. Is there a way to do so?
P.S I'm new to jQuery so please be gentle :)
You can save the id in a data- attribute:
<tr class="clickable-row" data-href="updatesingle" data-id="<%=id%>">
And, if you're going to use that ID with JSP, then you can pass it as a parameter to the other page:
window.document.location = $(this).data("href") + "?id=" + $(this).data("id");
But if you're going to get it with jQuery in the other page, you can save the ID into the sessionStorage:
sessionStorage.setItem('clickedUserID', $(this).data("id"));
window.document.location = $(this).data("href");
In the other page, you just get it from the sessionStorage and use it:
var userID = sessionStorage.getItem('clickedUserID');
// do something with the ID
Pro-tip: if you are only printing out a String into your JSP, you can simply just type it into the HTML (and save yourself the extra coding)
Here's my attempt to answer your question:
$(document).ready(function($) {
$(".clickable-row").click(function() {
// you can add the URL for the new page here like:
// var newLocation = "<URL for JSP>?paramName=" + paramValue
// this is just an example of how it would work
var newLocation = window.document.location + "?href=" + $(this).data("href");
alert( newLocation );
// oher values
console.log( $(this).find("td").eq(1).html() ); // 1 for id column, 2 for name, 3 for amount, etc.
window.document.location = newLocation;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<table class="table table-hover">
<tr>
<th>Serial</th>
<th>Cost ID</th>
<th>Cost Name</th>
<th>Cost Amount</th>
<th>Cost Date</th>
</tr>
<tr class="clickable-row" data-href="updatesingle1">
<td>1</td>
<td>id1</td>
<td>name1</td>
<td>amount1</td>
<td>date1</td>
</tr>
<tr class="clickable-row" data-href="updatesingle2">
<td>2</td>
<td>id2</td>
<td>name2</td>
<td>amount2</td>
<td>date2</td>
</tr>
<tr class="clickable-row" data-href="updatesingle3">
<td>3</td>
<td>id3</td>
<td>name3</td>
<td>amount3</td>
<td>date3</td>
</tr>
</table>
Related
I'm doing a school project in which I'm creating webpages to allow users to input and then display it on another page. I am only using javascript, html and css for the webpages.
On the Create An Event page is a form. I have saved all the input into local storage but now I am unsure on how to retrieve the data to display in on another page called Event History. Here are my codes:
function saveToStorage() {
var nameofevent=document.getElementById("name").value;
var pList=document.getElementsByName("pos");
var positions=[];
for (i=0; i<pList.length; i++){
positions.push(pList[i].value);
console.log(pList[i].value);
}
//for (i=0; i<positions.length; i++){
//console.log(positions[i].value);
//}
var venue= document.getElementById("venue").value;
var date=document.getElementById("date").value;
var starttime=document.getElementById("timeStart").value;
var endtime=document.getElementById("timeEnd").value;
var contact=document.getElementById("contact").value;
var email=document.getElementById("email").value;
var desc=document.getElementById("desc").value;
var one={"name":nameofevent,"pos":positions,"venue":venue,"date":date,"timeStart":starttime,"timeEnd":endtime,"contact":contact,"email":email,"desc":desc};
localStorage["CreateEvent"]=JSON.stringify(one);
return false;
}
Whenever the user submits the Create An Event form, the data that the user inputs will be displayed in a table in another page. Here are my codes for the table:
<h1>Events Created</h1>
<table border="1px" id="tab">
<thead>
<tr style=" font-size: 30px">
<th id="event">Name of event</th>
<th>Positions</th>
<th id="">Venue</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>eg. Name</td>
<td>eg. Position1, position2</td>
<td>eg. venue</td>
<td>eg. date</td>
<td>eg. start time</td>
<td>eg. end time</td>
</tr>
</tbody>
var saved=JSON.parse(localStorage.getItem("createEvent"));
alert(saved.name);
//etc
You can simply read from the localStorage in the same way, you wrote to it.
You could add this function to your js:
function loadEvents() {
//get the JSON Object from local storage
var event = JSON.parse(localStorage["CreateEvent"]);
//get the first row in the table
var firstRow = document.querySelector('table tbody tr');
//get the single tds
var eventName = firstRow.querySelector('td:nth-child(1)');
//put the data into the tds
eventName.innerHTML = event.name;
}
Call this function with <body onLoad="loadEvents()"in your View Events page.
Make sure you add the <script /> to the file.
This way it is very cumbersome to select the child nodes, so maybe you would want to put some classes in your markup.
I'm trying to generate a HTML table from an input Excel sheet using Apache POI in a JSP page. I have managed to code the part where the data is fetched from Excel and displayed as a HTML table, but the problem is some of the primary IDs has been duplicated in severals rows but they have different values in other rows. Example (2 Johns with Different Lastname):
<table>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>John</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
The code to generate the table :
out.println("<table>");
while (rowIter.hasNext())
{
row =(HSSFRow)rowIter.next();
input_fname = row.getCell(0);
input_lname = row.getCell(1);
input_age = row.getCell(2);
fname = input_fname.getRichStringCellValue().getString();
lname = input_lname.getRichStringCellValue().getString();
age = input_age.getRichStringCellValue().getString();
out.println("<tr>");
out.println("<td>"+fname+"</td>");
out.println("<td>"+lname+"</td>");
out.println("<td>"+age+"</td>");
out.println("</tr>");
}
}
out.println("</table>");
Please anyone advise me how can I merge the duplicated rows according to the Primary ID, First Name as below :
<table>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td rowspan="2">John</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>Doe</td>
<td>80</td>
</tr>
</table>
I have tried searching for similar question but i couldn't find any solution for my problem and I'm quite a beginner in Javascript and JQuery (maybe that's the problem). Any suggestions is much appreciated. Thanks in advance!
You are asking the wrong question. Wouldn't it be much easier to write the HTML correctly in the first place rather than try to do some merge on the HTML?
Thus, loop over the entries and put them in some suitable datastructure e.g. a Map keyed by fname and with a list as the value. Person class is a simple bean to hold the data.
Map<String, List<Person>> people = new TreeMap<String, List<Person>> ();
while (rowIter.hasNext())
{
row =(HSSFRow)rowIter.next();
input_fname = row.getCell(0);
input_lname = row.getCell(1);
input_age = row.getCell(2);
fname = input_fname.getRichStringCellValue().getString();
lname = input_lname.getRichStringCellValue().getString();
age = input_age.getRichStringCellValue().getString();
Person person = new Person(fname, lname, age);
if(! people.containsKey(person.fname)){
people.put(person.fname, new ArrayList<Person>());
}
people.get(person.fname).add(person);
}
}
Then loop over this data structure and write the HTML:
for(String key : people.keySet()){
List<Person> persons = people.get(key));
int rowSpan = persons.size();
//write the HTML accordingly.
}
You can:
add a class when printing the name in your back-end code e.g. out.println("<td class="fname">"+fname+"</td>");
and then with jQuery
var last_selected_name = "";
/* Get all the first names cells */
jQuery('td.fname').each(function(i,obj){
current_name = jQuery(obj).text();
/* check for repeated names */
if (current_name == last_selected_name)
{
jQuery("td.fname:contains('"+current_name+"')").each(function(index,object){
if (index == 0)
{
/* check if already has rowspan attribtue */
row_span = jQuery(object).attr('rowspan')?jQuery(object).attr('rowspan'):1;
/* add one */
row_span++;
/* include the new rowspan number */
jQuery(object).attr('rowspan',row_span)
}
else
{
/* delete the other first name cells */
jQuery(object).remove();
}
})
}
last_selected_name = current_name;
})
I'm trying to create a table with a JSON Object using Mustache.js.
I wanted it to show two rows, however it's only showing the second row only.
I suspect that the first row is being overwritten by the second when it's being bound again in the loop.
How do I work my way around it? Or is there a better structure I should follow?
Javascript:
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = JSON.parse(text);
$(document).ready(function() {
var template = $('#user-template').html();
for(var i in obj)
{
var info = Mustache.render(template, obj[i]);
$('#ModuleUserTable').html(info);
}
});
Template :
<script id="user-template" type="text/template">
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</script>
table:
<table border="1">
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
<tr id = "ModuleUserTable">
</tr>
</table>
In additon to your own solution, you should consider using mustache to repeat the row for you:
<script id="user-template" type="text/template">
{{#people}}
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
{{/people}}
</script>
var text = '[{"Fullname":"John", "WorkEmail":"john#gmail.com"},{"Fullname":"Mary", "WorkEmail":"mary#gmail.com"}]'
var obj = {people: JSON.parse(text)};
$(document).ready(function() {
var template = $('#user-template').html();
var info = Mustache.render(template, obj);
$('#ModuleUserTable').html(info);
});
I figured out that instead of
$('#ModuleUserTable').html(info);
it should be :
$('#ModuleUserTable').append(info);
Template should be :
<script id="user-template" type="text/template">
<tr>
<td>{{FullName}}</td>
<td>{{WorkEmail}}</td>
</tr>
</script>
and ID should not be on the table row tag. Instead it should be on the table itself:
<table border="1" id = "ModuleUserTable>
<tr>
<th>FullName</th>
<th>WorkEmail</th>
</tr>
</table>
The moment when it appends, it adds a new row into the table with the JSON data.
I have created an ASP.net MVC app and I have created a DataTable [DataTable.net] as follows:
<table id="invoiceTable">
<thead>
<tr>
<th>Invoice ID</th>
<th>Date</th>
<th>Reciept Date</th>
<th>Category</th>
<th>Total Value</th>
<th>Invoice Ref</th>
<th>Client</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#{
foreach (FreeAgentApp.Models.CustomInvoice _invoice in ViewBag.Invoices)
{
<tr>
<td>#_invoice.InvoiceId</td>
<td>#_invoice.Date</td>
<td>#_invoice.RecpDate</td>
<td>#_invoice.Category</td>
<td>#_invoice.TotalValue</td>
<td>#_invoice.InvoiceRef</td>
<td>#_invoice.Client</td>
<td>#_invoice.Status</td>
</tr>
}
}
</tbody>
</table>
And i can get the information from a row when its selected using javascript as follows:
// Row data
$(document).ready(function () {
oTable = $('#invoiceTable').dataTable();
oTable.$('tr').click(function () {
var data = oTable.fnGetData(this);
alert(data);
// ... do something with the array / object of data for the row
});
});
The variable data will provide a string of every value in the row separated by a comma as follows:
"000,26-01-14,27-01-14,001,1000,inv,something ltd,paid"
I want to have all these values separated. Note this could be done by splitting on the comma however a value in the table could contain commas.
How can I separate this string?
According to the DataTables documentation oTable.fnGetData(this); return an array filled with the data of the definitions in the row so you should be able to acces the data directly from data.
var invoiceId = data[0];
var date = data[1];
var recpDate = data[2];
// etc. etc.
Im trying too append data to a table with the tablesorter plugin (http://tablesorter.com)
Im using the following code:
<table id="sortme" border="1" style="width: 200px;">
<thead>
<tr>
<th>first name</th>
<th>last name</th>
<th>age</th>
</tr>
</thead>
<tbody>
<tr>
<td>will</td>
<td>smith</td>
<td>1</td>
</tr>
...................
</tbody>
</table>
Click me!
And:
$(document).ready(function() {
var i = 5;
$("#sortme").tablesorter({
sortList: [[2,0]]
});
$("#test").click(function() {
$("#sortme tbody").append('<tr><td>NEW</td><td>NEW</td><td>'+(i++)+'</td></tr>');
$("#sortme").trigger("update");
var s = [[2,0]];
$("#sortme").trigger("sorton",[s]);
return false;
});
});
Problem is the appended row stays at top, why?
See example: http://jsfiddle.net/jmU3Z/8/
In case anyone else stumbles across this.
By the time the "sorton" event is handled the DOM hasn't been assigned the table.config.parsers. The "sorton" event handling needs to be wrapped in a 1 millisecond timeout.
Replace the existing "sorton" bind in jquery.tablesorter.js (line ~803) with the following:
}).bind("sorton", function (e, list) {
var me = this;
setTimeout(function () {
$(this).trigger("sortStart");
config.sortList = list;
// update and store the sortlist
var sortList = config.sortList;
// update header count index
updateHeaderSortCount(me, sortList);
// set css for headers
setHeadersCss(me, $headers, sortList, sortCSS);
// sort the table and append it to the dom
appendToTable(me, multisort(me, sortList, cache));
}, 1);
You're problem is the [s]. You're sort parameter is already an array, just pass it the var not the var in an array.
$("#sortme").trigger("sorton",s);
Works for me, FF4.