I am not very familiar with JavaScript and AJAX.
I am developing a webpage that displays information return by a ยง.getJSON / JQuery request. But this function only works, when I start debugging. I know that the debugger corrects the timing and scope from other post on this topic. But I cannot find my mistake. I do not realy need a long explaination, because as I said before I am not very familiar with JavaScript/AJAX. This is the script-part in the page (you can ignore the addDropDown() and the departmentSelected() functions(as far as i know)):
<script type="text/javascript">
var isSelected = [];
$(addDropDown);
function addDropDown(){
$.getJSON("./api/persence/departments/all", function(data, status){
if(status !== "success"){
alert(status);
}else{
var dropdownHead = "<button class='btn btn-primary dropdown-toggle' type='button' data-toggle='dropdown'>Abteilungen<span class='caret'><\/span><\/button>";
var dropdownBody = "<ul class='dropdown-menu'>";
var i;
for(i = 0; i < data.length; i++){
dropdownBody = dropdownBody + "<li><a href='javascript:departmentSelected(" + i + "," + data[i].departmentId + ");'>";
dropdownBody = dropdownBody + data[i].departmentName;
dropdownBody = dropdownBody + " - ";
dropdownBody = dropdownBody + data[i].departmentCity;
dropdownBody = dropdownBody + "<\/a><\/li>";
}
dropdownBody = dropdownBody + "<\/ul>";
dropdownHead = dropdownHead + dropdownBody;
$("#dropdown-list").append(dropdownHead);
isSelected.length = i + 1;
}
});
}
function departmentSelected(position, value){
if((isSelected[position] !== value)){
isSelected[position] = value;
}else{
isSelected[position] = "false";
}
loadTable();
}
function loadTable(){
var tHead = "<br><div class='table-responsive'><table class='table'><thead><tr><th>#</th><th>Name<\/th><th>Beruf<\/th><th>Anwesend<\/th><th>Arbeitsplatz<\/th><\/tr><\/thead>";
var tBody = "<tbody>";
for(var i = 0; i < isSelected.length; i++){
var counter = 0;
if(isSelected[i] !== "false"){
$.getJSON("./api/persence/departments/" + isSelected[i]).then(function(result, status){
if(status !== "success"){
alert(status);
}else{
for(var i = 0; i < result.length; i++) {
var employee = result[i];
tBody = tBody + "<tr> <td>" + counter + "<\/td>";
tBody = tBody + "<td>" + employee.academicTitle + " " + employee.lastName + " " + employee.firstName + "<\/td>";
tBody = tBody + "<td>" + employee.job + "<\/td>";
tBody = tBody + "<td>";
if(employee.persenceStatus === "Y"){
tBody = tBody + employee.persenceSince;
}else{
// if(employee.absenceReason !== null){
tBody = tBody + employee.absenceReason;
// }
//else{
// tBody = tBody + " ";
//}
}
tBody = tBody + "<\/td>";
tBody = tBody + "<td>" + employee.workplace + "<\/td>";
tBody = tBody + "<\/tr>";
counter++;
}
}
});
}
}
tBody = tBody + "<\/tbody> <\/table> <\/div>";
tHead = tHead + tBody;
document.getElementById("outputTable").innerHTML = tHead;
}
My Problem: I can not find what I have done wrong in this scriptpart, because the debugger (firebug) is able to optimize the code while debugging so it works perfectly fine. But if I am not in debug-mode, only the "head-line" of the table is displayed (the information is missing).
Thanks for your help.
This problem is about the finding element in DOM. Sometimes Js faster than DOM and Js can't find specific element in html DOM. You need to define js code in onLoad.
$(function() {
$(addDropDown);
});
OR
$(document).ready(function(){
$(addDropDown);
});
Inportant Info: If you include jQuery don't use JS specific functions. Sometimes it crash with jquery. Just use jQuery functions.
Example:
not good : document.getElementById("outputTable")
good : '$.("#outputTable")'
Ok, I solved the problem myself: I had to put the following part into the function called by the jQuery request (function(result, status).....)
tBody = tBody + "</tbody> </table> </div>";
tHead = tHead + tBody;
document.getElementById("outputTable").innerHTML = tHead;
Related
I am creating a table using Ajax and JavaScript and using Spring Boot as a backend technology. So the scenario is:
There are two dropdowns one for selecting company name from list and with that company, corresponding truck list would be displayed. After selecting company name and truck from both the dropdowns, clicking on search button there would display a table with dynamic data of selected company and truck. So, for each created row there is select drop down in table row. So I want to display further data when selecting any of the option list from dropdown.
I want to display child row inside parent row after selecting any of the option from dropdown list using Ajax and JavaScript.
Below is my script where I am creating table with dynamic data:
function searchdata(){
var companyid = $("#searchQueryDD").val();
var truckid = $("#searchtruckdd").val();
var url = "api/gettablebycompanyandtruck";
$.post(url, {
companyid : companyid,
truckid : truckid,
limit : limit,
}, function(data, status) {
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var row = "", tripnumber="";
var newtrip = [];
var uniquetrip = {};
var row = "";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
tripnumber = list[i].tripnumber;
uniquetrip[tripnumber] = list[i];
}
for(var i in uniquetrip){
newtrip.push(uniquetrip[i]);
}
for(var i = 0; i < newtrip.length; i++){
row = row + "<tr>" +
"<td>"+newtrip[i].company.companyname+"</td>" +
"<td>"+newtrip[i].driver.username+"</td>" +
"<td>"+newtrip[i].truck.name+"</td>" +
"<td>"+newtrip[i].tripnumber+"</td>" +
"<input type='hidden' id='company_id' value='"+newtrip[i].company.companyid+"'>" +
"<input type='hidden' id='trip_number' value='"+newtrip[i].tripnumber+"'>"+
"<td><select onchange='getmorerows();' id='sub_trip'>" +
"<option selected disabled>Choose subtrip</option><option value='1'>1</option>" +
"<option value='2'>2</option><option value='3'>3</option></select></td>"+
"<td>"+newtrip[i].pickupdate+"</td>" +
"<td>"+newtrip[i].deliverydate+"</td>"+
"<td>"+newtrip[i].loadrate+"</td>" +
"<td>"+newtrip[i].dispatchfee+"</td>" +
"<td>"+newtrip[i].fuel+"</td>" +
"<td>"+newtrip[i].cardfee+"</td>" +
"<td>"+newtrip[i].onroadrepair+"</td>" +
"<td>"+newtrip[i].shoprepair+"</td>" +
"<td>"+newtrip[i].trailerrent+"</td>" +
"<td>"+newtrip[i].comcheck+"</td>" +
"<td>"+newtrip[i].advance+"</td>" +
"<td>"+newtrip[i].miscellenous+"</td>" +
"<td>"+newtrip[i].total+"</td>" +
"<td>"+newtrip[i].layover+"</td>" +
"<td>"+newtrip[i].grandtotal+"</td>" +
"<td>" +
"<a data-toggle='modal' data-target='#mode_payment' onclick=\"getpayment('"+newtrip[i].tripid+"');\">"
+"<i class='fa fa-paypal' aria-hidden='true' style='color:#3585a5'></i>" +
"</a>" +
"<a onclick=\"getTrip('"+newtrip[i].tripid+"');\">"
+"<i class='fa fa-pencil-square-o ml-3' style='color: #3384a4;'></i>" +
"</a>" +
"<a href='invoice?id="+newtrip[i].tripid+"'>"
+"<i class='fa fa-file-pdf-o ml-3' aria-hidden='true' style='color:red'></i>" +
"</a>" +
"</td>" +
"</tr>";
}
}else{
row = row + "<tr><td colspan='19' style='font-size: initial;font-family: initial;'>No Data Available.</td></tr>";
}
document.getElementById('searchresulttable').innerHTML = row;
$("#triptable").css('display','inline-block');
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
And below script is to handle onchange event on select options:
function getmorerows() {
var companyid = document.getElementById("company_id").value;
var tripnumber = document.getElementById("trip_number").value;
var subtrip = document.getElementById("sub_trip").value;
var url = "api/getbysubtrip";
$.post(url,{
companyid : companyid,
tripnumber : tripnumber,
subtrip : subtrip,
},function(data, status){
if (data.status == "OK") {
if (data.statusCode == 1) {
var list = data.response;
var childrow = "";
if(list.length > 0){
for(var i = 0; i < list.length; i++){
childrow = childrow + "<tr class='display-nonee'>" +
"<td>"+list[i].company.companyname+"</td>"+
"<td>"+list[i].company.companyname+"</td>"+
"<td>"+list[i].company.companyname+"</td>"+
"</tr>";
var tr = $(this).parent().parent().nextAll(':lt(2)');
if (tr.is(".display-none")) {
tr.removeClass('display-none');
} else {
tr.addClass('display-none');
}
}
}
document.getElementById('searchresulttable').innerHTML = childrow;
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
} else {
var error = data.responseMessage;
swal(error, "", "error");
}
});
}
Change one line in getmorerows()
document.getElementById('searchresulttable').innerHTML = childrow; to $('#searchresulttable').append(childrow);
This is my current code. What I am trying to accomplish is as follows.
If json[i].enabled is true, I need to check the corresponding checkbox. If not, leave it empty.
function createTable(json) {
var element = "";
var i;
for (i = 0; i < json.length; i++) {
element = element
+ '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
}
//Had forgotten to add this before.
element = element + '</tbody>';
$('#dataTable > tbody').remove();
$("#dataTable").append(element);
}
I tried it by including the following if condition but it fails.
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
So, how do I go about doing this? How do I access that particular checkbox in the loop?
Thanks!
Using string concatenation and a ternary operator:
'<tr><td><input type="checkbox"' + ( json[i].enabled== "TRUE" ? ' checked' : '' ) + '/></td><td>'
$('input[type="checkbox"]').prop('checked', true);
complete example:
var $table=jQuery('<table></table>');
for (i = 0; i < json.length; i++) {
var $tr=jQuery(
'<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>');
if(json[i].enabled== "TRUE"){
$tr.find('input["checkbox"]').prop('checked', true);
}
$table.append($tr);
}
$jQuery('body').append($table);
The checbox element has not been created yet in the DOM. So you have to put the html first. Then use
input[type="checkbox"]
to match an actual checkbox element. And at last, you might want to get the last checkbox only (in the last row of your table) with this selector :
mytable tbody tr:last input[type="checkbox"]
So you have the following code :
function createTable(json) {
var i;
for (i = 0; i < json.length; i++) {
// construct the html
element = '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
// put the html in the page
$('#mytable tbody').append(element);
if(json[i].enabled== "TRUE"){
// get the last inserted line in the table and check the checkbox
$('#mytable tbody tr:last input[type="checkbox"]').prop('checked', true);
}
}
}
Try this:
$('input[type="checkbox"]:eq(i)').prop('checked', true);
Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}
Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE
Hi I want to add image in table cell according to condition in table. I am using dynamic table as follow:
$.get('http://myDomain.com/RIA/topIndiaDetails.asp', function(data)
{
console.log("####"+data);
var up = new Image();
var down = new Image();
up.src = "../../jquery.mobile/images/up.png";
down.src = "../../jquery.mobile/images/down.png"
substr = data.split('$');
//alert(substr.length);
//var theader = '<table border="1">\n';
//<table id="auditOverview" border="1">
var theader = '<table border="1" id=\"tableId\">\n';
var tbody = '';
for (var out = 1;out<substr.length-1;out++)
{
//alert(substr[out]);
tbody += '<tr>';
var pra = substr[out].split('|^');
//alert('pra.length is: '+pra.length);
for (var i=0;i<pra.length-1;i++)
{
tbody += '<td>';
if (pra[i]=="Red")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/down.png'/>");
}
else if (pra[i]=="Green")
{
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
}
tbody += pra[i];
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
});
Now I am checking condition as if (pra[i]=="Green") then I want to add image in cell insted of "Green" string and same for Red string. Any help will be appreciated. Thanks in advance.
instead of :
pra[i].append("<img id='theImg' src='../../jquery.mobile/images/up.png'/>");
do
pra[i] = "<img id='theImg' src='../../jquery.mobile/images/up.png'/>";