Table rows are not rendering on separate lines - javascript

I am trying to render a table, wherein each row of data is on a separate line. From my understanding, this is the default behavior for how data between <tr></tr> tags is rendered. At least, that is how it is has always functioned for me.
This is the code I am using:
function GetLastTen(){
$.ajax({url: LastTen, success: function(result) {
var location = document.getElementById('l_ten');
location.innerHTML = "<table>\n";
function format(location,object){
location.innerHTML += '<tr>\n' +
'<td>' + object.id + '</a></td>\n' +
'</tr>\n';
}
$.each(result, function(elem){
format(location, result[elem]);
});
location.innerHTML += "</table>"
}});
}
The code obtains the proper data--there is nothing wrong with what I am getting from the API endpoint, but all the rows are on the same line.
I am using bootstrap 3.3.7 and the latest version of jQuery.

Try constructing a HTML string first into variable and setting the innerHTML once you are done:
var result = [{id:1},{id:2},{id:3}]
$(document).ready(function(){
var location = $("#l_ten")
var tableHTML = "<table>\n"
function format(object){
tableHTML += '<tr>\n<td>' + object.id + '</a></td>\n</tr>\n';
}
$.each(result, function(elem){
format(result[elem]);
});
location.html(tableHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="l_ten"></div>

Related

How can I clean table data using javascript empty method

In my code, I add an event listener to the pagination button. I can pass the page number to the function and set a new page number based on user input. Before changing the table data I want to clear the table. In this case, I am using datatable.empty() method but it gives me that the datatable.empty is not a function. Any idea how can I solve it?
function pageButtons(pages) {
var t = document.getElementById('test');
for (var page = 1; page <= pages; page++) {
//console.log(pages)
t.innerHTML += '<button id=' + page + '>' + page + '</button>';
}
document.getElementById('test').addEventListener("click", function (event) {
var newPageNumber = event.target.id;
var datatable = document.getElementById('data1');
state.page = newPageNumber;
datatable.empty();
console.log(state.page);
buildTable();
})
}

executing JS function and define variable from html

What I have is a page which is gathering a large list of data via jQuery. I am trying to limit the amount of results shown to a variable, and change the results shown on the list to create a false-page effect. Everything works via the same JS function, and relies on 1 variable to make everything work. Simple. I've removed all of the extra code to simplify everything
function myFunction() { var page = 1; console.log(page); }
I am looking for a way to call on this function, but change the variable 'page' from within html. Something along the lines of:
2
I have been looking on google (and still am) I just can't seem to find what I am looking for. I'm trying to avoid multiple pages/refreshing as this element is going to be used for a larger project on the same page.
UPDATE: I managed to pass the intended values through to a JS function like so...
function myFunction(page) { console.log(page); }
...and...
<input type='button' onclick='myFunction(value)' value='input page number'>
This seems the simplest way of doing what I need, what do you think?
Thanks for your help btw guys.
To do this you will need to move the page variable to be a parameter of myFunction
function myFunction(page) { console.log(page); }
Then you can just pass in whatever page number you would like
2
Sure, you can add the data-url attribute to your markup and select on the .link class to fetch the data-url attribute for each element thats part of that class.
I'm trying to avoid multiple pages/refreshing as this element is going
to be used for a larger project on the same page.
Sounds like you also want an AJAX solution.
$(document).ready( function()
{
//Add this on your call.html page
$(".link").click(function()
{
//location of test JSON file
var root = 'https://jsonplaceholder.typicode.com';
//your custom attribute acting as your 'variable'
var page = $(this).attr('data-url');
console.log("page = " + page);
//remove any previous html from the modal
$(".modal-content").empty();
//send a request to the server to retrieve your pages
$.ajax(
{
method: "GET",
//this should be updated with location of file
url: root + '/posts/' + page,
//if server request to get page was successful
success: function(result)
{
console.log(result);
var res = result;
var content = "<div class='panel-default'><div class='panel-heading'><h3 class='panel-title'>" + res.title + "</h3></div><i><div class='panel-body'>''" + res.body + "''</i></div><p><u> Master Yoda, (2017)</u></p><p class='page'> Page: " + page + "</p></div>";
$(".modal-content").html(content);
},
//otherwise do this
error: function(result)
{
$(".modal-content").html("<div class='error'><span><b> Failed to retrieve data </b></span><p> try again later </p></div>");
}
});
});
});
.error
{
border: 2px dotted red;
margin: 5px;
}
a
{
font-size: 20px;
}
.page
{
text-align: left;
padding: 0 15px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
<a class="link" data-url="1" data-toggle="modal" data-target="#Modal" href="test.html">Show Page 1</a>
<br />
<a class="link" data-url="2" data-toggle="modal" data-target="#Modal" href="">Show Page 2</a>
<div id="Modal" class="modal fade text-center">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
I seem to have figured out how to do this. I wanted to stray from using lots of libraries in the project and just wanted to keep things simple, using the above answers for guidance (and a little more digging), basically my end goal was to use jQuery to obtain a long list of data, and format this data into a multiple page list (for which I used a table for formatting purposes). Let's say it's a list of names. The JSON results output as:
[{"first_name":"Bob"},{"last_name":"Jones"}] // (key, value)
But when I passed this through to the HTML Table it was just displaying 1000s of results in a single list, and formatting the list was a pain. This was my solution:
<script>
var pageNum = ""; // define Page Number variable for later.
var resLimit = 35; // variable to specify the number of results per page
function updateList () {
$.getJSON(" Location of JSON results ", function(data) {
var pageCount = Math.round(data.length/resLimit); // calculate number of pages
var auto_id = ((pageNum-1)*resLimit) // use variables to give each result an id
var newListData = ""; // define this for use later
then define and pass "new list data" to HTML Table:
var newListData = "";
$.each(data.slice(auto_id, (pageNum*resLimit)), function(key, value) {
auto_id++;
newListData += '<tr>';
newListData += '<td class="id">' + audo_id + '</td>';
newListData += '<td class="id">' + value.first_name + '</td>';
newListData += '<td class="id">' + value.last_name + '</td>';
newListData += '</tr>';
});
$('# ID of table, data will replace existing rows ').html(newListData);
At this point if you set the value of pageNum to 1 you should see the first 35 results on the list, all with auto-incremented ID numbers. If you change it to 2 and refresh the page you should see the next 35, with the ID numbers following on from the first page.
Next I needed to create a button for each of the pages:
$('# ID of table, data will replace existing rows ').html(newListData);
function createButtons() {
var buttonArray = "";
for(i=0, x=pageCount; i<x; i++) {
buttonArray += '<input type="button" onclick="changePage('
+ (i + 1) + ')" value="' + (i + 1) + '">';
}
$('# ID of Span tags for button container ').html(buttonArray); }
createButtons();
}); }
</script>
Then create changePage() and a function to refresh the data in the list automatically without messing things up
<script>
var pageNum = "";
function changePage(page) {
if (pageNum < 1) { pageNum = 1; } // set pageNum when the page loads
if (page > 0) { pageNum = page; } // overwrite pageNum when 'page' variable is defined
updateList(); }
changePage(); // initialise to prevent delayed display on page load
// refresh function:
function refreshData() {
changePage(0); // define 'page' as 0 so that pageNum is not overwritten
window.setTimeout(refreshData, 5000); } // loop this function every 5 seconds to
refreshData(); //-- keep this list populated with current data.
And that should just about do it! At least it's working for me but I might have missed something (hopefully not lol). Hope this helps someone theres quite a few things involved in this that could be extrapolated and used elsewhere :)
thanks for help everyone.

jQuery selector unable to find table row class

Given an array of strings returned from an sql query, I am appending the data as rows into my html table via javascript:
loadUsers: function()
{ .
.
.
function displayUsersOnTable(response)
{
for(var i = 0; i < response.results.length; i++)
{
var contact = response.results[i];
var $newRow = $('<tr class="user-row">' +
'<td>' + contact.full_name + '</td>' +
'<td>' + contact.email + '</td>' +
'</tr>')
.data('user', contact);
$userTableBody.append($newRow);
}
}
}
Inside a different function that is called after loadUsers is called, I have this:
$('.user-row').click( function() {
window.alert("CLICKED");
});
When I run my site it won't register the click event. If I select the classes from my table row or table header it runs fine. I suspect the problem involves the fact that the table rows are dynamically generated. When I inspect element everything is in place. What am I missing?
try:
$(document).on('click', '.user-row', function() {
window.alert("CLICKED");
});

Append html data with inline script html data and to print

I need to append table data with html inside script. And append data for print
but here the table data is only shows in the print mode.
html
<div>
<p>Your content here</p>
<table id="toPrint">
<tr>
<td>Neil D'zousa</td>
<td>112233445566</td>
</tr>
</table>
</div>
<div id="notForPrint">
print
</div>
script
function open() {
var w = window.print();
var htmlTable2 = '<tr>' + '<th>Name</th>'
+ '<th>Phone</th>'+ '</tr>';
var html = $("#toPrint").html();
var t=html;
$(t).append(htmlTable2);
$(w.document.body).html(t);
}
$(function() {
$("a#print").click(open);
});
if anyone knew about this please share your answer.
with regards ...
Demo
var htmlTable2 = '<tr>' + '<th>Name</th>'
+ '<th>Phone</th>'+ '</tr>';
var html1 = $("#toPrint").append(htmlTable2);
var t=html1;
$(t).append(htmlTable2);
window.print();
Try this. I tested in chrome. It works fine
EDIT:
Response to your req: You have to chack whether dom[name,etc] is already [resent
$('#domHeader').length > 0 means already present.
if(! $('#domHeader').length)
{
var htmlTable2 = '<tr>' + '<th>Name</th>'
+ '<th>Phone</th>'+ '</tr>';
var html1 = $("#toPrint").prepend(htmlTable2); //peter is correct
//var t=html1;
//$(t).append(htmlTable2);
}
EDITED DEMO
UPDATE FINAL
The following should do it. The headers should be at the top:
function open() {
var htmlTable2 = '<tr><th>Name</th><th>Phone</th></tr>';
var html1 = $("#toPrint").prepend( htmlTable2 );
window.print();
}
The rest of your code should work fine.

Pass string from one function to the next javascript

I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;

Categories