How to expand new table data rows onscreen? - javascript

Question : I have a table displaying information for university courses. There is a column on the left with a + sign next to each row. When this is pressed, I need to display data about all the students on the course (I have this data ready and waiting). However, how do I reveal this new row of data on the screen? And how would I collapse it again?
Code :
$(document).ready(function(){
$.ajax({
url: 'http://xx.xxx.xxx.xx/getCourses.php',
dataType: 'jsonp',
jsonpCallback: "courses",
success: function( data ) {
courseData = data;
drawTable(data);
}
});
$("#dataTable").on('click', '.data-button',function(){
/* text change method */
$(this).text(function( _ , currText){
return currText === '+' ? '-' : '+';
});
/* class change */
$(this).toggleClass('active');
/* get data */
var id= $(this).data('id');
//Now reveal rows of students under this course.
var studentData = courseData.courses[id];
//HOW DO I EXPAND THE EXTRA DATA ROWS ONTO THE TABLE??
})
});
function drawTable(data) {
for (var i = 0; i < data.courses.length; i++) {
drawRow(data.courses[i]);
}
}
function drawRow(rowData) {
var button='<anyElement data-id="'+ rowData.id +'" class="data-button">+</anyElement>';
var row = $("<tr />")
row.append('<td>'+button+'</td>');/* no need to wrap html in "$()" */
/* append other cells*/
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.start + "</td>"));
row.append($("<td>" + rowData.end + "</td>"));
row.append($("<td>" + rowData.lecturer + "</td>"));
/* do append to DOM after row created , makes for less DOM insertions*/
$("#dataTable").append(row);
}
</script>
</head>
<body>
<table id="dataTable">
<tr>
<th>Course</th>
<th>Start</th>
<th>End</th>
<th>Lecturer</th>
</tr>
</table>
</body>
</html>
Example of The Desired Result :

Your question doesn't go into enough detail in terms of how the student data is structured but nonetheless, I've tried to come up with something, just to show how a show/hide toggle would work. Here is a JSBin: http://jsbin.com/wekepori/1/edit?html,js,output
Edit: I've updated my answer as new information on how the student data will be structured was provided in the question. Note, in my example the data is just a hardcoded dictionary as I don't have a server back-end to work with that contains your data. So, the actual network call to retrieve the student will have to be added instead of my hardcode.
HTML:
<table id="dataTable" border="1">
<tr>
<th>Id</th>
<th>Course</th>
<th>Start</th>
<th>End</th>
<th>Lecturer</th>
</tr>
</table>
JavaScript:
$(document).ready(function(){
// $.ajax({
// url: 'http://xx.xxx.xxx.xx/getCourses.php',
// dataType: 'jsonp',
// jsonpCallback: "courses",
// success: function( data ) {
// courseData = data;
// drawTable(data);
// }
// });
var data = {
courses: [{
id: 1,
start: 0,
end: 0,
lecturer: "Mr. Smith"
},
{
id: 2,
start: 0,
end: 0,
lecturer: "Mr. Boon"
}]
};
var courseData = data;
drawTable(data);
$("#dataTable").on('click', '.data-button',function(){
var showStudentRow = $(this).text() === '+' ? true : false;
/* text change method */
$(this).text(function( _ , currText){
return currText === '+' ? '-' : '+';
});
/* class change */
$(this).toggleClass('active');
/* get data */
var id= $(this).data('id');
//Now reveal rows of students under this course.
//var studentData = courseData.courses[id];
//HOW DO I EXPAND THE EXTRA DATA ROWS ONTO THE TABLE?? see below v v
var studentData = [{
id: 23,
name: "Joe Bloggs"
},
{
id: 34,
name: "Marry Brown"
},
{
id: 55,
name: "Alan James"
}
];
if (showStudentRow) {
var trCourseRow = $(this).parent().parent();
var newStudentRow = addHeaderStudentRow(id, trCourseRow);
newStudentRow = addStudentRow(id, newStudentRow, studentData[0]);
newStudentRow = addStudentRow(id, newStudentRow, studentData[1]);
newStudentRow = addStudentRow(id, newStudentRow, studentData[2]);
}
else {
removeStudentRow(id);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.courses.length; i++) {
drawRow(data.courses[i]);
}
}
function addHeaderStudentRow(courseRowId, courseRow) {
var row = $('<tr></tr>')
.css('font-weight', 'bold')
.addClass('student' + courseRowId)
.append('<td>Student Id</td><td colspan="4">Name</td>');
row.insertAfter(courseRow);
return row;
}
function removeStudentRow(courseRowId) {
$('.student' + courseRowId).remove();
}
function addStudentRow(courseRowId, courseRow, studentRowData) {
var row = $('<tr></tr>')
.css('font-weight', 'bold')
.addClass('student' + courseRowId);
row.append($('<td>' + studentRowData.id + '</td>'));
row.append($('<td colspan="4">' + studentRowData.name + '</td>'));
row.insertAfter(courseRow);
return row;
}
function drawRow(rowData) {
var button='<div data-id="'+ rowData.id +'" class="data-button">+</div>';
var row = $("<tr />");
row.append('<td>'+button+'</td>');/* no need to wrap html in "$()" */
/* append other cells*/
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.start + "</td>"));
row.append($("<td>" + rowData.end + "</td>"));
row.append($("<td>" + rowData.lecturer + "</td>"));
/* do append to DOM after row created , makes for less DOM insertions*/
$("#dataTable").append(row);
}

Related

Using jquery ajax need response from API to go into table HTML [duplicate]

Possible duplicate Nested elements
I'm getting from server-side ajax response (Json) and I'm trying to dynamically create table rows and append them to an existing table with id=records_table.
I tried to implement the solution in possible duplicate but it failed.
My response looks like that:
'[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]'
the require result is something like that:
<tr>
<td>9</td>
<td>Alon</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>Tala</td>
<td>5</td>
</tr>
I want to do something without parsing the Json so I tried to do the following, which of course was a disaster:
function responseHandler(response)
{
$(function() {
$.each(response, function(i, item) {
$('<tr>').html(
$('td').text(item.rank),
$('td').text(item.content),
$('td').text(item.UID)
).appendTo('#records_table');
});
});
}
From my solution I get only one row with the number 6 in all cells. What am I doing wrong?
Use .append instead of .html
var response = "[{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}]";
// convert string to JSON
response = $.parseJSON(response);
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.rank),
$('<td>').text(item.content),
$('<td>').text(item.UID)
); //.appendTo('#records_table');
console.log($tr.wrap('<p>').html());
});
});
Try this (DEMO link updated):
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#records_table').append(trHTML);
}
Fiddle DEMO WITH AJAX
Here is a complete answer from hmkcode.com
If we have such JSON data
// JSON Data
var articles = [
{
"title":"Title 1",
"url":"URL 1",
"categories":["jQuery"],
"tags":["jquery","json","$.each"]
},
{
"title":"Title 2",
"url":"URL 2",
"categories":["Java"],
"tags":["java","json","jquery"]
}
];
And we want to view in this Table structure
<table id="added-articles" class="table">
<tr>
<th>Title</th>
<th>Categories</th>
<th>Tags</th>
</tr>
</table>
The following JS code will fill create a row for each JSON element
// 1. remove all existing rows
$("tr:has(td)").remove();
// 2. get each article
$.each(articles, function (index, article) {
// 2.2 Create table column for categories
var td_categories = $("<td/>");
// 2.3 get each category of this article
$.each(article.categories, function (i, category) {
var span = $("<span/>");
span.text(category);
td_categories.append(span);
});
// 2.4 Create table column for tags
var td_tags = $("<td/>");
// 2.5 get each tag of this article
$.each(article.tags, function (i, tag) {
var span = $("<span/>");
span.text(tag);
td_tags.append(span);
});
// 2.6 Create a new row and append 3 columns (title+url, categories, tags)
$("#added-articles").append($('<tr/>')
.append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
.append(td_categories)
.append(td_tags)
);
});
Try it like this:
$.each(response, function(i, item) {
$('<tr>').html("<td>" + response[i].rank + "</td><td>" + response[i].content + "</td><td>" + response[i].UID + "</td>").appendTo('#records_table');
});
Demo: http://jsfiddle.net/R5bQG/
$.ajax({
type: 'GET',
url: urlString ,
dataType: 'json',
success: function (response) {
var trHTML = '';
for(var f=0;f<response.length;f++) {
trHTML += '<tr><td><strong>' + response[f]['app_action_name']+'</strong></td><td><span class="label label-success">'+response[f]['action_type'] +'</span></td><td>'+response[f]['points']+'</td></tr>';
}
$('#result').html(trHTML);
$( ".spin-grid" ).removeClass( "fa-spin" );
}
});
You shouldn't create jquery objects for each cell and row. Try this:
function responseHandler(response)
{
var c = [];
$.each(response, function(i, item) {
c.push("<tr><td>" + item.rank + "</td>");
c.push("<td>" + item.content + "</td>");
c.push("<td>" + item.UID + "</td></tr>");
});
$('#records_table').html(c.join(""));
}
Data as JSON:
data = [
{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}
]
You can use jQuery to iterate over JSON and create tables dynamically:
num_rows = data.length;
num_cols = size_of_array(data[0]);
table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");
header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);
$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})
Here is the size_of_array function:
function size_of_array(obj) {
size = Object.keys(obj).length;
return(size)
};
You can also add styling if needed:
$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');
Result:
This is working sample that I copied from my project.
function fetchAllReceipts(documentShareId) {
console.log('http call: ' + uri + "/" + documentShareId)
$.ajax({
url: uri + "/" + documentShareId,
type: "GET",
contentType: "application/json;",
cache: false,
success: function (receipts) {
//console.log(receipts);
$(receipts).each(function (index, item) {
console.log(item);
//console.log(receipts[index]);
$('#receipts tbody').append(
'<tr><td>' + item.Firstname + ' ' + item.Lastname +
'</td><td>' + item.TransactionId +
'</td><td>' + item.Amount +
'</td><td>' + item.Status +
'</td></tr>'
)
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
}
// Sample json data coming from server
var data = [
0: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test1", Lastname: "Test1", }
1: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test 2", Lastname: "Test2", }
];
<button type="button" class="btn btn-primary" onclick='fetchAllReceipts("#share.Id")'>
RECEIPTS
</button>
<div id="receipts" style="display:contents">
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Transaction</th>
<th>Amount</th>
<th>Status</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I have created this JQuery function
/**
* Draw a table from json array
* #param {array} json_data_array Data array as JSON multi dimension array
* #param {array} head_array Table Headings as an array (Array items must me correspond to JSON array)
* #param {array} item_array JSON array's sub element list as an array
* #param {string} destinaion_element '#id' or '.class': html output will be rendered to this element
* #returns {string} HTML output will be rendered to 'destinaion_element'
*/
function draw_a_table_from_json(json_data_array, head_array, item_array, destinaion_element) {
var table = '<table>';
//TH Loop
table += '<tr>';
$.each(head_array, function (head_array_key, head_array_value) {
table += '<th>' + head_array_value + '</th>';
});
table += '</tr>';
//TR loop
$.each(json_data_array, function (key, value) {
table += '<tr>';
//TD loop
$.each(item_array, function (item_key, item_value) {
table += '<td>' + value[item_value] + '</td>';
});
table += '</tr>';
});
table += '</table>';
$(destinaion_element).append(table);
}
;
You could do it something like this:
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function(){
$.ajax({
url: '<Insert your REST API which you want GET/POST/PUT/DELETE>',
data: '<any parameters you want to send as the Request body or query string>',
dataType: json,
async: true,
method: "GET"
success: function(data){
//If the REST API returned a successful response it'll be stored in data,
//just parse that field using jQuery and you're all set
var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>';
$.each(data, function(idx, obj){
//Outer .each loop is for traversing the JSON rows
tblSomething += '<tr>';
//Inner .each loop is for traversing JSON columns
$.each(obj, function(key, value){
tblSomething += '<td>' + value + '</td>';
});
tblSomething += '</tr>';
});
tblSomething += '</tbody>';
$('#tblSomething').html(tblSomething);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Hey, something went wrong because: ' + errorThrown);
}
});
});
</script>
<table id = "tblSomething" class = "table table-hover"></table>
jQuery.html takes string or callback as input, not sure how your example is working... Try something like $('<tr>').append($('<td>' + item.rank + '</td>').append ...
And you have some definite problems with tags fromation. It should be $('<tr/>') and $('<td/>')
I do following to get JSON response from Ajax and parse without using parseJson:
$.ajax({
dataType: 'json', <----
type: 'GET',
url: 'get/allworldbankaccounts.json',
data: $("body form:first").serialize(),
If you are using dataType as Text then you need $.parseJSON(response)

Is there a setting to stop the display of "No data available in table" in the DataTable?

Initially my table has no data and I get "No data available in table" which is the expected functionality.
I'd like to have no text or row created as I will be populating the table via Ajax depending on user action.
Is there a setting to stop the display of this row in the table? I can't seem to find one. This code works but the first row reads "No data available in table". This is the jQuery code:
$.ajax({
type: 'GET',
url: '/Home/postInformationofConferenceTitle',
dataType: "JSON",
success: function (data) {
$.post("/Home/selectRooms", { xtitle: data.xglobalTitle }, function (data) {
var ndx = 0;
$.each(data.xroom_name, function (key, value) {
var Xroom_name = data.xroom_name[ndx];
var Xroom_plan = data.xroom_plan[ndx];
var column =
('<tr>' +
'<td>' +
'<div class="img-container">' +
'<img src="../../assets/img/room-plan/' + Xroom_plan + '" alt="..." id="imgsrc">' +
'</div>' +
'</td>' +
'<td id="imgname">' + Xroom_name + '</td>' +
'<td class="text-right">' +
'<i class="fa fa-edit"></i>' +
'</i>' +
'</td>' +
'</tr>');
document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;
ndx++;
});
});
}
})
I guess you might be looking at the language settings of datatables.
language : {
"zeroRecords": " "
},
(Note the space between " ". (Its a hack but found it to be useful for now.)
$(document).ready(function () {
var serverData = [
]
var table = $('#example').DataTable({
language : {
"zeroRecords": " "
},
data: serverData,
columns: [
{ data: "name" },
{ data: "age" },
{ data: "isActive" },
{ data: "friends" },
],
'columnDefs': [{
'targets': 2,
'render': function (data, type, full, meta) {
let checked = ''
if (data) {
return '<input type="checkbox" checked / >';
}
else {
return '<input type="checkbox" / >';
}
return data;
}
},
{
'targets': 3,
"render": function (data, type, full, meta) {
var selectInitial = "<select>";
var selectClosing = "</select>";
var options = '';
$.each(data, function (key, value) {
options = options+"<option value="+value.id+">"+value.name+"</option>";
});
return selectInitial+options+selectClosing;
}
}
],
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js'></script><link rel='stylesheet prefetch' href='https://cdn.datatables.net/1.10.9/css/jquery.dataTables.css'>
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>isActive</th>
<th>friends</th>
</tr>
</thead>
</table>
It works for me.
var someTableDT = $("#some-table").on("draw.dt", function () {
$(this).find(".dataTables_empty").parents('tbody').empty();
}).DataTable(/*init object*/);
Below worked for me:
$(document).ready(function () {
$("#TABLE_ID").DataTable();
$(".dataTables_empty").empty();
});
Next CSS worked for me to totally hide that block (not only delete text):
.dataTables_empty
{
display:none;
}

Refer specific row on click of button in table data fetched from JSON using only JavaScript

I am learning AJAX and not able to find how to refer a particular row in a table which is fetched from a .json file. Actually I want the respective data on click of the respective edit button in the row. It should be displayed in the <p> tag just below the table.
Heres my script
<script>
function myFunction() //on click function to fetch data from json
{
var counter;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(xhttp.readyState == 4 && xhttp.status == 200)
{
var data = JSON.parse(xhttp.responseText);
mydata(data);
}
};
xhttp.open("GET", "employee.json");
xhttp.send();
counter ++ ;
}
function mydata(data){ //data to be shown and fetch
var output = "<table>";
var output = "<th>Employee Code</th>" +
"<th>Name</th>" +
"<th>Joining Date</th>" +
"<th>Salary</th>"+
"<th>Edit</th>";
//var i in each items[i]
for(var i in data)
{
output += '<tr>' +
'<td>' + data[i].empcode + '</td>' +
'<td>' + data[i].name + '</td>' +
'<td>' + data[i].joining + '</td>'+
'<td>' + data[i].salary + '</td>' +
'<td>' + '<button onclick="edit()">Edit</button>' +
'</tr>';
}
output +="</th>" + "</th>" + "</th>" + "</th>" + "</th>";
output += "</table>";
document.getElementById('demo').innerHTML = output;
function edit(){
document.getElementById("para").innerHTML = data[1].empcode;
}
}
function edit(){ //edit function to display related data from json file. Right now i can only display data which i mentioned in editTextData().
var edit = new XMLHttpRequest();
edit.onreadystatechange = function(){
if(edit.readyState == 4 && edit.status == 200){
var editData = JSON.parse(edit.responseText);
editTextData(editData);
}
};
edit.open("GET", "employee.json", true);
edit.send();
}
function editTextData(textData){
document.getElementById("para").innerHTML = textData[2].empcode;
}
</script>
This is the JSON data :
[{
"empcode" : 1,
"name": "sid",
"joining" : "13 march",
"salary" : 60000
},
{
"empcode" : 2,
"name": "andrew",
"joining" : "15 march",
"salary" : 65000
},
{
"empcode" : 3,
"name": "blake",
"joining" : "18 march",
"salary" : 70000
}
]
This is the html code :
<h1>AJAX Employee</h1>
<div>
<table id="demo"> </table>
</div>
<button onclick="myFunction()" ">Fetch Info</button>
<p id="para"> </p>
This is the result i am getting
Result table after clicking fetch button. When i click any edit button it shows the 3rd employee number
Your edit handler can figure out which button was clicked, which row it belongs to, and which empcode that was. The key is the this value that gets passed into the edit handler.
You're assigning the handler inline, which isn't ideal, so you will need to make a change to that part:
'<td>' + '<button onclick="edit(this)">Edit</button>'
Now the button is being passed into edit as the first parameter, so:
function edit(btn) { //edit function to display related data from json file.
// get the TR that this button is in
var tr = btn.parentNode.parentNode;
// get the collection of tds
var tds = tr.querySelectorAll("td");
// get the contents of the first TD, that should be the empcode
var empcode = tds[0].innerText;
// do whatever you need to with empcode, or the other values in this record
console.log("empcode = " + empcode + ", name = " + tds[1].innerText);
}

ActionLink in jquery table

i am new to mvc and jquery,
i have created one table with jquery but i don't know how we add one actionlink in each row and also i need to call one function on the onclick event.
my code is given bellow
function loadData(data) {
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Id</th><th></th>');
thead.append('<th>Username</th>');
tab.append(thead);
$.each(data, function (i, val) {
var trow = $('<tr></tr>');
trow.append('<td>' + val.empID + '</td>');
trow.append('<td>' +"" + '</td>');
trow.append('<td>' + val.empName + '</td>');
trow.append('<td>' + '#Html.ActionLink("Edit", "Edit", new { id = val.empID })' + '</td>');
tab.append(trow);
});
here i got one error
"val is not in the current context"
please anyone help me to add one actionlink with click event.
You can achieve this by changing your code as below.
function loadData(data) {
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Id</th><th></th>');
thead.append('<th>Username</th>');
tab.append(thead);
$.each(data, function (i, val) {
var trow = $('<tr></tr>');
trow.append('<td>' + val.empID + '</td>');
trow.append('<td>' +"" + '</td>');
trow.append('<td>' + val.empName + '</td>');
trow.append('<td></td>');
tab.append(trow);
});
Try this and let me know, if you required anymore information.
Below Code Work Perfectly and Bind Table dynamically with Control.
function bindTable (data)
{
usersTable = $('<table><thead><tr>'
+ '<th style="width: 300px;">Col 1</th><th>Col 2</th><th>Col 3</th><th>Col 4</th><th>Col 5</th>'
+ '</tr></thead ></table>').attr({ class: ["dataTable row-border hover"].join(' '), id: "table", style: "border: 1px solid; background-color:#d2d2d2;" });
var rows = new Number("10");
var cols = new Number("4");
var tr = [];
if (data != null) {
for (var i = 0; i < data.length; i++) {
var row = $("<tr></tr>").attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(table);
$("<td></td>").html(data[i].Col1).appendTo(row);
$("<td></td>").html(data[i].Col2).appendTo(row);
$("<td></td>").html(data[i].Col3).appendTo(row);
$("<td></td>").html(data[i].Col4).appendTo(row);
$("<td></td>").html($('<a href=/ControllerName/Action?ParamId='+data[i].Id+'>Action</a>')).appendTo(row);
}
}
table.appendTo("#Div");
$("#table").DataTable({
"aoColumns": [null, null, null, null, { "bSortable": false }]
});
}

How to access via jquery to select controls created dynamically

I have created dynamically some select controls(a.k.a. groupbox) but every time that I try to access to one of them if get the followig error:
Uncaught TypeError: undefined is not a function
Here is the code:
var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
Where parseInt(buttonElementId + 1 is always a number so the error is not there
<html>
<head lang="en">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"> <!-- load fontawesome -->
<style>
body { padding-top:80px; }
html, body, #wrapper
{
width: 100%;
height: 100%;
}
</style>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="container">
<div id="information"></div>
<div id="tableInformation"></div>
<div id="goBack"></div>
<br/>
<div id="inputDiv"></div>
<br/>
<br/>
<div id="UserGuide"></div>
</div>
<script src="js/jquery-1.11.js"> </script>
<script>
var apiUrl = 'http://localhost/devices';
$( document ).ready(function() {
// Handler for .ready() called.
jsonGETRequest(apiUrl, jsonExampleData);
});
$(document).on('click', ':button' , function() {
// reference clicked button via: $(this)
$("#UserGuide").empty();
var buttonElementId = $(this).attr('id');
if(buttonElementId.indexOf("btnShowFunc") > -1) {
buttonElementId = buttonElementId.replace("btnShowFunc","");
deviceUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) + 1)].cells[1].innerHTML;
goBack = "firstAPIRequest";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
} else if(buttonElementId.indexOf("btnGoBack") > -1 ) {
switch (goBack) {
case "firstAPIRequest":
goBack = "";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl, jsonExampleData);
removeGoBackInputDiv();
break;
case "secondAPIRequest":
goBack = "firstAPIRequest";
$("#tableInformation tbody").remove();
jsonGETRequest(apiUrl + "/" + deviceUID + "/functions", jsonExampleDataFunctions);
removeGoBackInputDiv();
break;
}
}else if(buttonElementId.indexOf("btnRunFunc") > -1) {
goBack = "secondAPIRequest";
buttonElementId = buttonElementId.replace("btnRunFunc","");
var functionUID = document.getElementById("mytable").rows[(parseInt(buttonElementId) +1)].cells[2].innerHTML;
var method =$("#slt" + (parseInt(buttonElementId + 1))).children("option").is("selected").text();
$("#tableInformation tbody").remove();
$("#inputDiv").empty();
// /jsonPOST(apiUrl '/functions/' + functionUID )
}
});
function loadDataIntoDeviceGrid(jsonData) {
//$("#tableInformation").addClass("table table-responsive table-bordered");
var tbl=$("<table/>").attr("id","mytable");
$("#tableInformation").append(tbl);
$("#mytable").append("<tr>" + "<th>dal.device.status</th>" + "<th>dal.device.UID</th>"
+ "<th>dal.device.driver</th>" + "<th>service.id</th>" +"<th></th>" + "</tr>");
for(var i=0;i<jsonData.length;i++)
{
var tr = "<tr>";
var td1 = "<td>"+jsonData[i]["dal.device.status"]+"</td>";
var td2 = "<td>"+jsonData[i]["dal.device.UID"]+"</td>";
var td3 = "<td>"+jsonData[i]["dal.device.driver"]+"</td>";
var td4 = "<td>"+jsonData[i]["service.id"]+"</td>";
//#Deprecated var dataList = fillSelectControl(jsonData[i]["objectClass"]); #Deprecated
var btn = "<td>" + "<button id='btnShowFunc"+ i + "' class='btn btn-success btn-lg'>See function</button>" + "</td></tr>";
$("#mytable").append(tr + td1 + td2 + td3 + td4 + btn );
}
$("#mytable").addClass("table table-responsive table-bordered");
}
function loadInformationDeviceGrid() {
$("#UserGuide").addClass("alert alert-info");
$("#UserGuide").html("<h3>Getting devices list:</h3><br/> "+
"Using this request, you can retrieve a list of all the available devices."+
"For every device, among other info, there is the indication of the device unique ID, which" +
"can be used to directly access to the device and the indication of the device driver (ZigBee, Bluetooth, etc.).<br/>If you want see some request response example please visit this <a href='#'>site</a>");
}
function removeGoBackInputDiv() {
$("#inputDiv").empty();
$("#btnGoBack").remove();
}
function loadDataIntoFunctionsGrid(jsonData) {
$("#mytable").append("<tr>" + "<th>function.device.UID</th>"
+ "<th>service.id</th>" + "<th>function.UID</th>" + "<th>operation.names</th>" + "<th></th>" + "</tr>");
var tr, td2, td3, td4, dt2, btn;
for(var i = 0; i < jsonData.length; i++) {
tr = "<tr>";
//#Deprecated td1 = "<td>" + jsonData[i]["CLASS"] + "</td>";
td2 = "<td>" + jsonData[i]["al.function.device.UID"] + "</td>";
td3 = "<td>" + jsonData[i]["service.id"] + "</td>";
td4 = "<td>" + jsonData[i]["dal.function.UID"] + "</td>";
//#Deprecated dt1 = fillSelectControl(jsonData[i]["objectClass"]);
dt2 = fillSelectControl(jsonData[i]["dal.function.operation.names"], i);
btn = "<td>" + "<button id='btnRunFunc"+ i + "' class='btn btn-success btn-lg'>Run</button>" + "</td></tr>";
$("#mytable").append(tr + td2 + td3 + td4 + dt2 + btn );
}
createGoBackButton();
createInputTextParameters();
}
function loadInformationFunctionsGrid() {
$("#UserGuide").addClass("alert alert-info");
$("#UserGuide").html("<h3>Getting device functions:</h3><br/>"
+ "This API is used to retrieve the list of the available functions supported by the device. For"
+ "example a Smart Plug has two functions: one to retrieve the energy consumption and another"
+ "'boolean' function useful to change the status of the smart plug (ON/OFF). Every function"
+ "indicates the id, which can be used to access directly the function and the list of the operation"
+ "that can be invoked on the function.<br/>"
+ "P.S. If he want use a function that want some parameters he must write these into the dedicated textbox. If the API needs more parameters separate these using comma. <br/>"
+ "Example of parametes: <br/> <code>'type':'java.math.BigDecimal'</code><br/> <code>'value':1</code> <br/> etc...");
}
function createGoBackButton() {
var btn = '<button id="btnGoBack" class="btn btn-warning btn-lg">Go Back</button>';
$("#goBack").append(btn);
}
function createInputTextParameters() {
var lbl ="<label>Paramters</label>";
var txt ='<input type="text" class="form-control" name="email">';
$("#inputDiv").addClass("form-group");
$("#inputDiv").append(lbl);
$("#inputDiv").append(txt);
}
function fillSelectControl(obj, id) {
var dataList = "<td><select id='slt"+ id +"'>";
for(var j = 0; j < obj.length; j++)
dataList = dataList + "<option value='" + obj[j] + "'>" + obj[j] + "</option>";
return dataList = dataList + "</select></td>";
}
var json = "";
var goBack = "";
var deviceUID;
function jsonGETRequest(url, dataExample){
$.getJSON(apiUrl, function(data) {
alert(JSON.stringify(data));
this.json = data;
})
.done(function() {
$("#information").addClass("alert alert-success");
$("#information").text("getJSON request succeeded!");
if(goBack == "") {
loadDataIntoDeviceGrid(jsonExampleData);
loadInformationDeviceGrid();
} else if (goBack=="firstAPIRequest") {
loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
loadInformationDeviceGrid();
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
//alert('getJSON request failed! ' + textStatus);
$("#information").addClass("alert alert-danger");
$("#information").text("Impossible get data from API, it will be use example data" + errorThrown);
if(goBack == "") {
loadDataIntoDeviceGrid(jsonExampleData);
loadInformationDeviceGrid();
} else if (goBack=="firstAPIRequest") {
loadDataIntoFunctionsGrid(jsonExampleDataFunctions);
loadInformationFunctionsGrid();
} else if(goBack=="secondAPIRequest") {
}
})
.always(function() { });
}
function jsonPOST(url, method, paramters, dataExample) {
}
var jsonExampleData = [
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test123",
"dal.device.driver": "ZigBee",
"service.id": 28,
"objectClass": [
"org.osgi.service.dal.Device"
]
},
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test456",
"dal.device.driver": "ZigBee",
"service.id": 29,
"objectClass": [
"org.osgi.service.dal.Device"
]
},
{
"dal.device.status": 2,
"dal.device.UID": "ZigBee:test789",
"dal.device.driver": "ZigBee",
"service.id": 30,
"objectClass": [
"org.osgi.service.dal.Device"
]
}
];
var jsonExampleDataFunctions = [
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test123",
"service.id": 27,
"dal.function.UID": "ZigBee:test123:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
},
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test456",
"service.id": 26,
"dal.function.UID": "ZigBee:test456:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
},
{
"CLASS": "ismb.pert.jemma.dummydevice.DummyFunction",
"dal.function.device.UID": "ZigBee:test789",
"service.id": 25,
"dal.function.UID": "ZigBee:test789:testButton",
"objectClass": [
"org.osgi.service.dal.Function"
],
"dal.function.operation.names": [
"getData",
"reverse",
"setFalse",
"setTrue"
]
}
];
</script>
</body>
</html>
.is() returns a true/false value, it does not continue the jQuery chain, therefor there is no .text() function to call
As DevishOne points out in the comments to get the selected option's text do:
=$("#slt" + (parseInt(buttonElementId + 1))).children("option:selected").text();
Split that in to multiple steps and check for the particular result:
button = $("#slt" + (parseInt(buttonElementId + 1)));
if ( button )
{
childs = button.children("option");
if ( childs .....
Whenever there's no option selected, you are unable to catch that since you refer directly to a method .text() of null.

Categories