how to store array data in table? - javascript

I wanted the user to enter any alphabet in a text field, when he/she clicks on the Find! button, it will go through my php file and find a list of words that start with that alphabet (of course it's only a limited amount of words). And I want to output it to a table, with 5 columns, each cell containing one word.
Something like this:
in my HTML:
<label>
Enter any alphabet:
<input name="alphabet" type="text" id="alphabet"></label>
<input type="button" value="Find!" id="goFind">
<table border="1" id="output">
</table>
and Javascript:
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
var bunchOfWords = function (data) {
var listOfWords = "";
if(!Array.isArray(data)) {
return false;
}
else {
for(i = 0; i < data.length; i = +5) {
listOfWords += "<tr><td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td></tr>";
}
}
};
$("#goFind").click(function () {
var theWord = $("#alphabet").val();
$("#output").html("Loading..."); //gives the user an indication that it's loading
$.getJSON("wordslookup.php", "startswith=" + theWord, listOfWords);
});
});
Can't seem to figure out what's wrong.

listOfWords is out of scope in $.getJSON also its not a function, you should pass bunchOfWords to $.getJSON instead. To put the data in the table simply replace the current inner html, $("#output").html(listOfWords);

Related

How to loop through and print out correctly

I Know why I'm getting undefined but i have no idea how to solve.
Tried to put null, but it is taking in as a text
var text ='{"employees":[' +
'{"name":"Tony","mobile":"99221111","email":"tony#json.com"},' +
'{"name":"Linda","mobile":"98981111","email":"linda#json.com"},' +
'{"name":"Patrick","mobile":"90902222","email":"patrick#json.com"},' +
'{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for(var i in obj.employees)
{
document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>"
+ "<td>" + obj.employees[i].email + "</td></tr>";
}
Hi, for Isabella there is no email, hence I'm getting undefined when I loop through to print out their details on html, however what I'm expecting is for the email portion to be empty in the table for Isabella. Is there a way to solve it?
You can use logical OR (|| in JavaScript), which will use the second value (empty string in this case) if the first value (email) is undefined:
var text = '{"employees":[' +
'{"name":"Tony","mobile":"99221111","email":"tony#json.com"},' +
'{"name":"Linda","mobile":"98981111","email":"linda#json.com"},' +
'{"name":"Patrick","mobile":"90902222","email":"patrick#json.com"},' +
'{"name":"Isabella","mobile":"99552222"}]}';
obj = JSON.parse(text);
for (var i in obj.employees) {
document.getElementById("table").innerHTML += "<tr><td>" + obj.employees[i].name + "</td>" + "<td>" + obj.employees[i].mobile + "</td>" +
"<td>" + (obj.employees[i].email || '') + "</td></tr>";
}
<table id="table"></table>

Dynamically Create HTML Table with Pagination

I'm trying to create an html table with pagination. I'm requesting JSON data via $.get call using JQuery which is an async call. The solution I currently have duplicates the HTML code whenever a new page is selected. I know this is an asynchronocity but I'm not exactly sure what the best method to overcome this would be.
<script type="text/javascript">
function generateTable(currentPage) {
this.URL = "https://jsonplaceholder.typicode.com/posts";
$.getJSON(URL, function(data) {
const pages = Math.ceil(data.length / 10);
for(let i = currentPage*10; i<(currentPage*10)+10; i++ ) {
let post = data[i];
let tblRow = "<tr>" + "<td>" + post.userId + "</td>" + "<td>" + post.id + "</td>" + "<td>" + post.title + "</td>" + "<td>" + post.body + "</td>" + "</tr>"
$(tblRow).appendTo("#jsonData tbody");
}
for (let i = 1; i <= pages; i++) {
let pagingHtml = "<a href=# onclick=generateTable("+(i-1)+")>"+" "+i+" "+"</a>"
$(pagingHtml).appendTo("#paging");
}
})
}
generateTable(0);
</script>
Before populating the HTML, clear out the current rows from the page:
$("#jsonData tbody,#paging").empty();
This assumes that those two parent elements only have dynamic content. If not, you should reference container elements that only have dynamic content (so no headers, footers, ...etc).

I can't show my array in JavaScript

I have some simple code in JavaScript. I was going to create code to add first name, last name and age of students from the client by click on "Add Student" button, and show the list of students including the one just added by clicking on the "Show Students" button.
The add action is successful, but when I click on "Show Students" button it just shows me a table without any information(First Name,Last Name,Age).
var students = new Array();
var i = 0;
function AddStudent()
{
var patt = /i[a-z]/;
var Fname = prompt("enter first name");
var Lname = prompt("enter last name");
var Age = prompt("enter age");
var std= {fname : Fname,lname : Lname,age : Age }
students[i++] =std;
}
function ShowStudents()
{
var table = "<table style='background-color:greenyellow; border:solid;'>";
table += "<tr><th>نام</th><th>نام خانوادگی</th><th>سن</th></tr>"
for( var j=0;j<students.length;j++)
{
table += "<tr>"
table += "<td>" + students[j].fname +"</td>"
table += "<td>" + students[j].lname + "</td>"
table += "<td>" + students[j].age + "</td>"
table +="</tr>"
}
table += "</table>";
document.getElementById("ShowStudents").innerHTML = table;
}
<input type="button" value="Add Student" onclick="AddStudent();"/>
<input type="button" value="Show Students" onclick="ShowStudents();"/>
<div id="ShowStudents"></div>
I think that your browser can not execute instructions without " ; " , so try to add it in this lines :
table += "<tr><th>نام</th><th>نام خانوادگی</th><th>سن</th></tr>"
for( var j=0;j<students.length;j++)
{
table += "<tr>"
table += "<td>" + students[j].fname +"</td>"
table += "<td>" + students[j].lname + "</td>"
table += "<td>" + students[j].age + "</td>"
table +="</tr>"
}
because for me it works like a charm.
i had some comment in my js page and useless functions.finally i clean the comment and useless functions and it worked!

Sort HTML Table, that gets appended via JQuery

Hello i'm trying to use Tablesorter(https://github.com/christianbach/tablesorter) to sort a table of mine which i generate throu JQuery.appends. This is how my code looks:
$(document).ready(function() {
*Lotsa more code .....*
$.get("../skillqueue",{keyid: keyid, charid: charid},function(xmlskillqueue){
console.log("XML Skillqueue");
console.log(xmlskillqueue);
//Variables for
var rowsets = xmlskillqueue.getElementsByTagName("rowset");
var skillrows;
for(var i = 0; i < rowsets.length; i++){
if(rowsets[i].getAttribute("name") == "skillqueue"){
skillrows = rowsets[i].getElementsByTagName("row");
}
}
//Defines Table Headers
$("#tableskillqueuelist").append(
"<thead>" +
"<tr>" +
"<th>Order: </th> "+
"<th>Skill Name: </th> "+
"<th>Training to: </th> "+
"<th>Starts:</th> "+
"<th>Ends:</th> "+
"</tr> "+
"</thead>"+
"<tbody>"
);
for(var i = 0; i < skillrows.length; i++){
(function(i, skillrows) {
$.get("../getitemname", {itemid:skillrows.getAttribute("typeID")},function(itemname){
$("#tableskillqueuelist").append(
"<tr> " +
"<td>" + skillrows.getAttribute("queuePosition") + ". " +
"<td>" + itemname + "</td>" +
"<td>" + "|Train to: " + skillrows.getAttribute("level") + "</td>" +
"<td>" + "|Training Starts: " + skillrows.getAttribute("startTime") + "</td>" +
"<td>" + "|Training Ends: " + skillrows.getAttribute("endTime") + "<td>" +
"</tr>"
);
})
})(i, skillrows[i]);
}
//Ends the table body
$("#tableskillqueuelist").append("</tbody>");
});
});
Now i'm wondering what i need to do to have it successfully run the $("#tableskillqueuelist").tablesorter(); method. Since it seems like whenever i try and run it, the #tableskillqueuelist seems to be empty.
You need to tell table sorter that you've changed the data and that you want to sort it by triggering events.
Example from the docs: http://tablesorter.com/docs/example-ajax.html
$("table").tablesorter();
$("#ajax-append").click(function() {
$.get("assets/ajax-content.html", function(html) {
// append the "ajax'd" data to the table body
$("table tbody").append(html);
// let the plugin know that we made a update
$("table").trigger("update");
// set sorting column and direction, this will sort on the first and third column
var sorting = [[2,1],[0,0]];
// sort on the first column
$("table").trigger("sorton",[sorting]);
});
return false;
});
HTH

Copy a row of data to the textfields of same page on selecting a row through radio button

Dynamically generating rows by jquery
$("#showbtn").on("click", function() {
var tblRow;
$.getJSON('multimob.action', $("#mobileno").serialize(), function(data) {
if (data.mobileno === null) {
alert("Wrong Mobile No.,please Check");
} else {
$.each(data.ls, function(index, value) {
var count = index;
tblRow = $("<tr><td> <input type='radio' id='chk' name='chk' onclick='copyrecord('" + count + "');'/></td><td id='fidrow" + count + "'>" + value.id + "</td>"
+ "<td>" + value.name + "</td>" + "<td>"
+ value.mobileno + "</td>" + "<td>" + value.addres + "</td></tr>");
alert(count + tblRow.toString());
$("#farmTable tbody").append(tblRow);
});
});
The data rows are dynamically created ,Once I select the radio button, it should take the data from that row and it has to be copied to the textfields in the same page .
Help me to get rid of this iisue.
Try this example
Use class
<input type='radio' id='chk' name='chk' class="chk"/>
HTML
$(document).on('click','.chk',function(){
var text=[];
$(this).parents('tr').find('td:not(:first)').each(function(){
console.log($(this).text())
text.push($(this).text())
});
$('#name').val(text[0]);
$('#no').val(text[1]);
$('#add').val(text[2])
});
DEMO
As per your comment: I can change the id and name as 'chk"+count+"' something like this. But how can I copy the row data on selecting the row by radio button
You can get it this way:
$("#farmTable").on('change', '[id^="chk"]', function(){
var tblVals = $("#farmTable tr").map(function(){
return $(this).find('td:not(:first)').text();
});
console.log(tblVals);
});

Categories

Resources