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!
Related
I have a function which loads a html table with sql data query and a html page to display the table when i click the button but it is not showing the table, it just shows the url changing to match my search but does not display the table
Function code:
function Search()
{
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function()
{
search_array = JSON.parse(request.responseText);
result();
}
searchrestaurant.send(JSON.stringify(search));
}
function result()
{
var table = document.getElementById("result");
table.innerHTML = "";
result = search_array.length
for (var count = 0; count < result; count++)
{
// data from sql
var restaurant_name = search_array[count].restaurant_name;
var Description = search_array[count].Description;
var location = search_array[count].location;
var thumbnail = search_array[count].thumbnail;
var price = search_array[count].price;
var rating = search_array[count].avg_rating;
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>"+
"<td>" +"<a href = 'detailed_restaurant.html' target ='_blank'>"+"<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>"+"</td>" +
"<td>"+"<a href = 'detailed_restaurant.html' target ='_blank'>"+ restaurant_name + "</td>" +
"<td>"+ location + "</td>" +
"<td>"+ Description + "</td>" +
"<td>"+ price + "</td>" +
"<td>"+ rating + "</td>"
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
Html:
<body>
<form id = "SearchForm">
<label>Search </label>
<input type="text" id="searchinput" name="restaurantName">
<input type="button" onclick="Search()" value="Submit">
</form>
<div class="container"></div>
<div id="result" class="row"></div>
</div>
I have already loaded the script into the html site but it is just take my input and does not display the table i created
Concatenation operator is missing after "<td>" + rating + "</td>".
Add the + operator. like "<td>" + rating + "</td>" +.
function result() {
var table = document.getElementById("result");
table.innerHTML = "";
result = 5
for (var count = 0; count < result; count++) {
// data from sql
var restaurant_name = 1;
var Description = 'ddf';
var location = 'location';
var thumbnail = 1;
var price = 'Price';
var rating = 'rating';
//table to show all sql data
var AllrestaurantTable = "<table class = fixed style=width:100% border=1px>" +
"<tr>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + "<img src ='" + thumbnail + "'style=width:100px;height:100px;></img>" + "</td>" +
"<td>" + "<a href = 'detailed_restaurant.html' target ='_blank'>" + restaurant_name + "</td>" +
"<td>" + location + "</td>" +
"<td>" + Description + "</td>" +
"<td>" + price + "</td>" +
"<td>" + rating + "</td>" +
"</tr>" +
"</table>";
table.insertAdjacentHTML('beforeend', AllrestaurantTable);
}
}
result();
<div id="result" class="row"></div>
</div>
You have to pass the search array in your result function.
function Search() {
var search = new Object;
search.restaurantName = document.getElementById("searchinput").value; //get input
var searchrestaurant = new XMLHttpRequest();
searchrestaurant.open("POST", Search_url, true);
searchrestaurant.setRequestHeader("Content-Type", "application/json");
searchrestaurant.onload = function () {
search_array = JSON.parse(request.responseText);
result(search_array);
}
searchrestaurant.send(JSON.stringify(search));
}
Hope this will work.
I have a table that I have dynamically created from a JSON object I am getting from the server via an ajax request. I am trying to append buttons to the end of each of the rows in the table. The table has seven rows, thus I have 7 buttons. I want something like the following. I want to set a javascript variable to create each individual button with the following parameters :
(obviously with different ids)
<input type="button"id="submit-button2"class="btn btn primary"value="Submit" />
so that I can set up an array of buttons of these variables in javascript such as the following:
var buttons = [
button1,
button2,
button3,
button4,
button5,
button6,
button7
];
Then I can iterate through my JSON object and the buttons array appending them to the table (named requestTable) like the following :
for(var j = 0; j < request[0].DepartmentApprovals.length && buttons.length; j++) {
$("<tr>" + "<td id=\"Departments\">"
+ request[0].DepartmentApprovals[j].Department +":" + "</td>"
+ "<td input type=\"text\" id=\"ApproverLanId\" contenteditable=\"false\" class=\"underline\">"
+ request[0].DepartmentApprovals[j].Approver.LanId + "</td>"
+ "<td>" + "Date:" + "</td>"
+ "<td contenteditable=\"false\" class=\"underline\">" + request[0].DateApproved + "</td>"
+ "<td>" + buttons[j].outerHTML + "</td>"+ "</tr>").appendTo("#requestTable");
}
The table data works, My issue has been that I am able to get a button to append and show if I use the document.getElementById of an existing button already created elsewhere on the form, but clearly I do not want this, I want them dynamically created with differing ids that exist only in the scope of the table. I am not sure how to accomplish this through javascript.
I am not 100% sure if this is what you want, but this code should add a button with a dynamic ID (submit-button-1, submit-button-2, etc ...) inside the last cell of each row:
for (var j = 0; j < request[0].DepartmentApprovals.length && buttons.length; j++) {
var appendHTML = '';
appendHTML += '<tr>';
appendHTML += '<td id="Departments">' + request[0].DepartmentApprovals[j].Department + ':</td>';
appendHTML += '<td input type="text" id="ApproverLanId" contenteditable="false" class="underline">' + request[0].DepartmentApprovals[j].Approver.LanId + '</td>';
appendHTML += '<td>Date:</td>';
appendHTML += '<td contenteditable="false" class="underline">' + request[0].DateApproved + '</td>';
appendHTML += '<td><input type="button" id="submit-button-' + (j + 1) + '" class="btn btn primary" value="Submit" /></td>';
appendHTML += '</tr>';
appendHTML.appendTo('#requestTable');
}
try this
var button = document.createElement("button");
button.innerHTML ="/*put name of button here*/";
// 2. Append somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener ("click", function(){/*put what button does here*/}
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
I have following code. Now I want to get the hidden column value based on user selected row. I also want to highlight the entire row, not only the e.target.
Can someone please help me.
function getTermdetailsQuerySuccsess(sender, args) {
var listEnumerator = Termsitems.getEnumerator();
var datatable = document.getElementById("TermList");
while (listEnumerator.moveNext()) {
var oListItem = listEnumerator.get_current();
//var firstName = listEnumerator.get_current().get_item('Title');
//var secondName = listEnumerator.get_current().get_item('LastName');
var termID = listEnumerator.get_current().get_item('ID');
var startdate = listEnumerator.get_current().get_item('startdate');
var enddate = listEnumerator.get_current().get_item('Enddate');
var termtype = listEnumerator.get_current().get_item('TermType');
var Hours = listEnumerator.get_current().get_item('Hours');
var EdNone = listEnumerator.get_current().get_item('EdNoned');
var Specialty = listEnumerator.get_current().get_item('Specialty');
var Subspecialty = listEnumerator.get_current().get_item('Subspecialty');
var Hospital = listEnumerator.get_current().get_item('Hospital');
var DEMT = listEnumerator.get_current().get_item('DEMT');
var Supervisor = listEnumerator.get_current().get_item('Supervisor');
rowcount = rowcount + 1;
$("#TermList").append("<tr style='border-bottom:1px silver solid' align='middle' class='gradeA'>" +
"<td align='left' style='display:none'>" + termID + "</td>" +
"<td align='left'>" + startdate + "</td>" +
"<td align='left'>" + enddate + "</td>" +
"<td align='left'>" + termtype + "</td>" +
"<td align='left'>" + Hours + "</td>" +
"<td align='left'>" + EdNone + "</td>" +
"<td align='left'>" + Specialty + "</td>" +
"<td align='left'>" + Subspecialty + "</td>" +
"<td align='left'>" + Hospital + "</td>" +
"<td align='left'>" + DEMT + "</td>" +
"<td align='left'>" + Supervisor + "</td>" +
"</tr>");
}
}
$('#TermList').click(function (e) {
var tr = $(e.target).parent().index() ;
alert(tr);
alert($(e.target).text()); // using jQuery
// var Cells = tr.e.getElementsByTagName("td");
$(e.target).addClass('row-highlight');
var confirmationM = confirm("Do you want to edit this term deatils ?");
if (confirmationM == true) {
confirmation = "You pressed OK!";
}
else {
confirmation = "You pressed Cancel!";
$(e.target).removeClass('row-highlight');
}
});
$('#TermList').click(function (e) {
var tr = $(e.target).parent().index() ;
alert(tr);
alert($(e.target).text()); // using jQuery
// var Cells = tr.e.getElementsByTagName("td");
$(e.target).addClass('row-highlight');
var table = $("#TermList")[0];
var cell = table.rows[tr].cells[1];
alert(cell);
var confirmationM = confirm("Do you want to edit this term deatils ?");
if (confirmationM == true) {
confirmation = "You pressed OK!";
}
else {
confirmation = "You pressed Cancel!";
$(e.target).removeClass('row-highlight');
}
});
I have following code. Now I want to get the hidden column value based on user selected row. I also want to highlight the entire row, not only the e.target.
Can someone please help me.
You have a lot of ways to improve/optimize your code. For example, instead of calling $(e.target) each time, you should save it into a variable: var $target = $(e.target), same thing for listEnumerator.get_current(), why do you call it all the time when you saved the value into oListItem ?!
But anyway, it's not your question.
Instead of binding the full table, you could bind only the TD: $('#TermList').click(function (e) { becomes $('#TermList').on('td', 'click', function(e) {
Then, to find the row, you just need to do:
var $td = $(this); // here it's your selected cell
var $tr = $td.parent(); // here it's your selected row
$tr.addClass('row-highlight'); // highlight the row
And to find the value in the first cell:
alert($tr.find('td:first').text()); // return the value of the first cell
I hope it helps.
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);