How to get appended accodian in JavaScript - javascript

I get companies from firebase database and append it to html using javascript. This is the code.
function loadcompanies() {
var leadsRef = database.ref('companies');
leadsRef.on('value', function(snapshot) {
if (snapshot.exists()) {
var content = '';
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
content += '<tr class="header" class="clickable">';
//content += '<tr class="header">';
content += '<td style="width: 55px; color: #42957F">'+childData.rooms+'</td>';
content += '<td id="companyName" onclick="getrooms(this)" data-toggle="collapse" data-target="#accordion1" style="width: 102px; font-weight: bold">'+childData.company+'</td>';
content += '<td style="width: 60px;">'+childData.code+'</td>';
content += '<td><i class="fas fa-plus-circle plus"></i>Add Rooms';
content += '</td>';
content += '</tr>';
//companyName.innerHTML += '<div>'+childData.company+'</div>';
//document.getElementById("companyName").innerHTML = childData.company;
//alert(childData.company);
console.log(childData.rooms.length);
});
$('#abctable').append(content);
}
});
}
When I load the page and click one of the companies, I get the name of that company using the id #companyform in javascript and by using that id I again use the firebase and get its rooms. This is the code.
function getrooms(x) {
name = $(x).closest('tr').find('#companyName').text();
//var rowIndex = $(x).closest('tr').index();
var leadsRef= database.ref('companies/' + name + '/nrooms');
leadsRef.on('value', function(snapshot) {
if (snapshot.exists()) {
var content= '';
snapshot.forEach(function(Snapshot){
var childData= Snapshot.val();
var key = Snapshot.key;
content+= '<tr style="background-color: #F2F2F2; color: #42957F">';
content+= '<td style="background-color: none" id="accordion1" class="collapse"></td>';
content+= '<td id="accordion1" class="collapse"></td>';
content+= '<td id="accordion1" class="collapse"></td>';
content+= '<td style="width: 170px;" id="accordion1" class="collapse">'+key+'</td>';
content+= ' <td style="width: 250px; font-size: 13px;" id="accordion1" class="collapse">'+childData.roombeacon.uuid+'</td>';
content+= '<td style="width: 90px;" id="accordion1" class="collapse">'+childData.roombeacon.major+'</td>';
content+= ' <td style="width: 100px;" id="accordion1" class="collapse">'+childData.roombeacon.minor+'</td>';
content+= ' <td style="width: 110px;" id="accordion1" class="collapse">'+childData.roombeacon.enter+'</td>';
content+= ' <td style="width: 85px;" id="accordion1" class="collapse">'+childData.roombeacon.docking+'</td>';
content+= '<td style="width: 45px;" id="accordion1" class="collapse">'+childData.roombeacon.tx+'</td>';
content+= ' <td style="font-size: 13px; width: 195px; margin-left:50px;" id="accordion1" class="collapse">'+childData.dockbeacon.uuid+'</td>';
content+= ' <td style=" width: 80px;" id="accordion1" class="collapse">'+childData.dockbeacon.major+'</td>';
content+= ' <td style="width: 110px;" id="accordion1" class="collapse">'+childData.dockbeacon.minor+'</td>';
content+= ' <td style="width: 110px;" id="accordion1" class="collapse">'+childData.dockbeacon.tx+'</td>';
content+= ' </tr>';
console.log(childData.roombeacon.length);
console.log(childData);
});
$('#abctable').append(content);
}
});
// alert(name);
}
The problem is that this program I have written is not correctly working, like every room is not loading after the company. It is printing at the end of all the companies listen, and when I click the company multiple times it does not close the according and keep on printing the value from database.
This is what it gives me when i click Devstop, It should print after Devstop row. and on clicking Devstop multiple times it is printing the rows multiple times,

I guess the root cause is the duplicated id property shared across your HTML.
Take following as an example, every element in your loop shares the same id property, which leads to your undesired result.
forEach{
<td id="companyName">
}
forEach{
<td id="accordion1">
}
Above is nested in a forEach loop, so elements sharing the same id are produced.
HTML doesn't allow more than one element assigned with the same id.
Your code has too many errors like this.
I hope following code sample will enlighten you a little bit and you can differentiate every id by appending the current loop index to it.
var content = "";
snapshot.forEach(function(childSnapshot, index) {
content += '<td id="companyName' + index + '">';
});

Related

How to correctly send data to the server from the table?

I apologize for possible grammatical errors, this text was translated through Google translate.
I'm not very good at programming yet, I'm learning right away in practice. Now I'm making a Django web application for warehouse management.
I have a select with a list of products that is loaded via api, and when the select is selected, a row with the product is added to the table
success: function (res) {
let invoiceRow = document.querySelector(".invoice-add-table table tbody tr.add-elements").insertAdjacentHTML('beforebegin', '<tr class="invoice-row">' +
'<td align="right" class="fixed">'+ res.articul +'</td>' +
'<td class="name" align="left"><span title="'+ res.name +'" style="text-decoration: underline; cursor: pointer;">'+ res.name +'</span></td>' +
'<td align="right" class="fixed"><input name="quantity" value="1" class="ta-right fixed" type="text"></td>' +
'<td align="right" class="fixed"><input name="last_buy_price" value="'+ res.last_buy_price +'" class="ta-right fixed" type="text"></td>' +
'<td align="right" class="fixed"><input name="summ" value="" class="ta-right fixed" type="text"></td>' +
'<td align="right" class="fixed"><input name="sell_price" value="'+ res.sell_price +'" class="ta-right fixed" type="text"></td>' +
'<td align="right"><div style="display: flex;" class="edit-tool-table"><span class="iconify" data-icon="bx:trash" style="color: white;" data-width="20"></span></div></td>'+
'</tr>');
$(".add-items-select")[0].selectize.clear()
Question:
How do I identify each row to send it to the server, as well as the data in the inputs that are responsible for the quantity and price? There can be as many lines as you want, I don't understand how to get them on the server
Thanks

How to get textbox values from a particular row where user is entering value?

I am adding data to html table dynamically on a button click using loadbooks function. When user clicks on this button, the table is filled with data dynamically.
<button id="button" onclick="loadbooks()"></button> function loadbooks() { ... ... for(var j in indivudvalbookdetails) { // if(indivudvalbookdetails[j]['barcode'] !="") //{ count++; $('.library_info_tbl tbody').append('
<tr>' + '
<td class="text-center centeralign"> ' + data[i]['callno'] + '</td>' + '
<td class="text-center centeralign"> ' + data[i]['subject'] + '</td>' + '
<td class="text-center centeralign"> ' + data[i]['title'] + ' </td>' + '
<td class="text-center centeralign"> ' + data[i]['isbn'] + '</td>' + '
<td class="text-center centeralign"> ' + data[i]['author'] + ' </td>' + '
<td class="text-center centeralign"> ' + indivudvalbookdetails[j]['acquisitionno'] + '</td>' + '
<td class="text-center centeralign">
<div class="btn-group">' + '
<input type="text" id="barcodedb'+id+'" value="'+indivudvalbookdetails[j]['barcode']+'" class="form-control hide">'+ '
<input type="text" id="barcode'+id+'" value="'+indivudvalbookdetails[j]['barcode']+'" class="form-control barcode">'+ '
<p id="barcodeerror'+id+'" style="color:red; display:none;">Already Assigned</p>'+ '
</div>
</td>' + '
</tr>'); id++; // } } ... }
I am showing how one row is rendered in browser
<tr><td class="text-center centeralign"> 14</td><td class="text-center centeralign"> Communication</td><td class="text-center centeralign"> Nueral Network </td><td class="text-center centeralign"> 6578975667</td><td class="text-center centeralign"> kggfiuigfuit </td><td class="text-center centeralign"> 54</td><td class="text-center centeralign"><div class="btn-group"><input type="text" id="barcodedb0" value="jkyifujyirkruf" class="form-control hide"><input type="text" id="barcode0" value="jkyifujyirkruf" class="form-control barcode"><p id="barcodeerror0" style="color:red; display:none;">Already Assigned</p></div></td></tr>
Similary there are many other rows rendered in the browser.
Please note that there are two textboxes one gets hidden by class="hide"(used for comparision operation latter).
Now the user will enter something in one of the textbox with ids barcode0 or barcode1 etc.
Please have a look at below function which I am using for retrieving textbox value
$('#library_info_tbl tbody tr td').on("keyup", "input:nth-child(2)", function(j) {
var barcode = $("#barcode" + j).val().trim();
var barcodedb = $("#barcodedb" + j).val().trim();
$("#barcodeerror" + j).css("display", "block");
});
Basically I have perform comparisions and other thing on the textbox values on that textbox where user is entering or entered some value and that textbox is present in the row of the table.
The above jquery on change event of textbox is not getting triggered...
To find unique id for each row, You could give each row an id and then get the id using
var thisRow = $(this).closest('tr');
var thisRowId = thisRow.attr('id');
Then you can write
var barcode = $("#barcode" + thisRowId).val().trim();

Open bootstrap table row in new table with possible field editor

I'm using bootstrap table library in my app that to render table with massive data and I need to open row in additional editable table. I found a lot of info in internet how to open row in model and put edited code to my app that to display row info inside div but cannot set it that to open it in editable table. I provide the plunker example.
Updated Cause I didn't get any work solution, I've tried to fix it by myself, so I know the solution isn't so good but for now it works for me. The question is still asking, how to edit field of new rendered table?
This is function of my solution:
$(function () {
var $result = $('#form');
$('#table').on('click-row.bs.table', function (e, row, $element) {
$('.success').removeClass('success');
$($element).addClass('success');
//alert('Selected name: ' + getSelectedRow().text);
function getSelectedRow() {
var index = $('#table').find('tr.success').data('index');
return $('#table').bootstrapTable('getData')[index];
}
$result.html(
'<table border="0" align="left" style="padding: 10px; margin: 10px; font-size: 14px; color: #0f0f0f">' + '<h3>'+
'<tr align="left" style="padding: 10px; margin: 10px;">' + '<td style="font-weight: bold;">Name</td>' + '<td> </td>' + '<td>' + getSelectedRow().name + '</td>' + '</tr>' +
'<tr align="left" style="padding: 10px; margin: 10px;">' + '<td style="font-weight: bold;">Structure</td>' + '<td> </td>' + '<td>' + getSelectedRow().stargazers_count + '</td>'+ '</tr>'+
'<tr align="left" style="padding: 10px; margin: 10px;"> '+ '<td style="font-weight: bold;">Class</td>' + '<td> </td>' + '<td>' + getSelectedRow().forks_count + '</td>'+ '</tr>'+
'<tr align="left" style="padding: 10px; margin: 10px;"> '+ '<td style="font-weight: bold;">Description</td>' + '<td> </td>' + '<td>' + getSelectedRow().description + '</td>'+ '</tr>'+
'</h3>' + '</table>'
);
})
});
You can use modals of boostrap, will open a modal. Check the documentation on http://getbootstrap.com/javascript/#via-javascript, just add the html, css and js references and call this code:
$('#table').on('click-row.bs.table', function (e, row, $element){ $('#myModal').modal('show') //Will be call the modal when you click a row
})
And you can pass all the information to the modal via javascript. Hope you understand me. :)
Not sure if I get what you need but i add this code on the
html:
<div id="form">
<input type="text" placeholder="Title1" id="titleForm1"></input>
<input type="text" placeholder="Title2" id="titleForm2"></input>
<input type="text" placeholder="Title3" id="titleForm3"></input>
<input type="text" placeholder="Title4" id="titleForm4"></input>
</div>
js:
$('#table').on('click-row.bs.table', function (e, row, $element) {
/*$result.html(
'<pre>' +
JSON.stringify(row, null, 1).replace(/,|}|{/g, " ")
//JSON.stringify(row).replace(/,/g, "<br/>")
+ '</pre>'
);*/
$('#titleForm1').val(row.name);
$('#titleForm2').val(row.stargazers_count);
$('#titleForm3').val(row.forks_count);
$('#titleForm4').val(row.description);
console.log(row);
})
Hope it helps you.

Jquery chevron icon not toggling down with accordion row when collapsed

First, My jfiddle: http://jsfiddle.net/34y943qq/
I have a bootstrap table with accordion properties that expands child rows when clicked. When I click another row, it expands, as well as collapses the previously opened row. This works, however the chevron icons I am using to indicate drop-down status don't seem to flip back.
I made a change http://jsfiddle.net/34y943qq/1/, but this also seems to not cause previous toggled chevrons to collapse. The only way I can get a chevron to toggle back is clicking directly on a row to open/close it.
Here's the jscript I added:
$(this).find('span').closest('.chevron_toggleable')
.not(this)
.toggleClass('glyphicon-chevron-up glyphicon-chevron-down');
I've also tried moving the ".not(this)" up to the find('span') but this doesn't seem to work either.
What am I missing?
here's the code to generate the table:
if (mysqli_num_rows($result)) {
echo '<table id="dasTable" cellpadding="0" cellspacing="0" class="table table-hover table-bordered tablesorter">';
echo '<thead>';
echo '<tr><th>Service ID</th><th>Assigned Namespace</th><th>DAS Station</th><th>Ingest Completed</th><th>Currently Ingesting</th><th>Offsite going to DAS</th><th>Mounted</th></tr></thead>';
echo '<tbody>';
// Generate rows from current das information
while ($row2 = mysqli_fetch_row($result)) {
// Format cell background based on content
$sidvalue = $row2[0];
$station = $row2[1];
$used = $row2[2];
$attacheddate = $row2[3];
$starteddate = $row2[4];
$ingestcomplete = $row2[5];
$ingesting = $row2[6];
$updating = $row2[7];
$mounted = $row2[8];
$totaljobs = $row2[9];
$remainingjobs = $row2[10];
$assigned = $row2[11];
echo '<tr class="accordion-toggle" data-toggle="collapse" id="', $sidvalue, '" data-target=".', $sidvalue, '">';
echo '<td class="rowtd"><span class="chevron_toggleable glyphicon glyphicon-chevron-down"></span> ', $sidvalue, '</td>';
echo '<td class="rowtd">', $assigned, '</td>';
echo '<td class="rowtd">', $station, '</td>';
echo '<td class="rowtd">', $ingestcomplete, '</td>';
if ($ingesting == 'GREEN') {
echo '<td class="success">YES</td>';
} else {
if ($ingestcomplete != 'NO') {
echo '<td class="success">NO</td>';
} else {
echo '<td class="danger">NO</td>';
}
}
if ($updating == 'GREEN') {
echo '<td class="success">NO</td>';
} else {
echo '<td class="danger">YES</td>';
}
if ($mounted == 'GREEN') {
echo '<td class="success">YES</td>';
} else {
if ($ingestcomplete != 'NO') {
echo '<td class="success">NO</td>';
} else {
echo '<td class="danger">NO</td>';
}
}
echo '</tr>';
Actually, I see where it's called twice:
// create the sub row
echo '<tr class="expand-child collapse ', $sidvalue, '">';
echo '<td class="h4" colspan="3"><b>Attached Date:</b> ', $attacheddate, '</td>';
$usedgb = round($used / 1024 / 1024 / 1024);
echo '<td class="h4" colspan="4"><i class="fa fa-hdd-o fa-lg"></i> ', $used, ' Bytes (', $usedgb, ' GB)</td>';
echo '</tr>';
echo '<tr class="expand-child collapse ', $sidvalue, '">';
echo '<td class="h4" colspan="3"><b>Ingest Start Date:</b> ', $starteddate, '</td>';
echo '<td class="h4" colspan="4">';
echo '<div class="progress">';
if ($remainingjobs == 0) {
$jobsdone = $totaljobs - 1;
$percentdone = round($jobsdone / $totaljobs * 100);
echo '<div class="progress-bar progress-bar-info progress-bar-striped active" role="progressbar" aria-valuenow="', $percentdone, '" aria-valuemin="0" aria-valuemax="100" style="width:', $percentdone, '%">Last Job</div>';
} else {
$jobsdone = $totaljobs - $remainingjobs;
$percentdone = round($jobsdone / $totaljobs * 100, 1);
echo '<div class="progress-bar progress-bar-info progress-bar-striped active" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:', $percentdone, '%"><b>', $jobsdone, '/', $totaljobs, ' (', $percentdone, '%)</b></div>';
}
echo '</div>';
echo '</td>';
echo '</tr>';
}
The reason they are both called "expand child collapse, is due to a SO question I found a while back on how to make expanding rows...I'm trying to find the link now, but I believe the gist was that each sub row needed the same collapse name so when the parent row was clicked, it would collapse all children rows.
Edit: here we go Creating Accordion Table with Bootstrap
That example has 1 sub row for each expanding row, I added a second row to be expanded with the same name, based on code found here: http://www.bootply.com/122871
DEMO: http://jsfiddle.net/rn07jq35/2/
Check the first three lines compare to the performance of the rest
Was at work and didnt ave time to try things.
I have edit the answer to this
$(document).ready(function () {
$(function () {
$("#dasTable").tablesorter();
});
});
$('.collapse').on('show.bs.collapse', function (e) {
$("#dasTable").find('.collapse.in').collapse('hide');
var targetx = $(this).data('trigger');
$(targetx).find('span').toggleClass('glyphicon-chevron-up glyphicon-chevron-down');
});
$('.collapse').on('hide.bs.collapse', function (e) {
var targetx = $(this).prev('.accordion-toggle').find('span');
var targetx = $(this).data('trigger');
$(targetx).find('span').toggleClass('glyphicon-chevron-up glyphicon-chevron-down');
});
The thing about child is this
<tr class="accordion-toggle" data-toggle="collapse" id="1dc4" data-target=".1dc4">
<td class="rowtd"> <span class="chevron_toggleable glyphicon glyphicon-chevron-down"></span> 1dc4</td>
<td class="rowtd">Gen2_SJC9</td>
<td class="rowtd">adsdas5</td>
<td class="rowtd">NO</td>
<td class="success">YES</td>
<td class="success">NO</td>
<td class="success">YES</td>
</tr>
<tr class="expand-child">
<td colspan="7">
<div class="container collapse 1dc4" data-trigger="#1dc4">
<div class="left"><b>Attached Date:</b>2015-08-26 16:42:04</div>
<div class="right"><i class="fa fa-hdd-o fa-lg"></i> 2883577569280 Bytes (2686 GB)</div>
<div class="left"><b>Ingest Start Date:</b> 2015-08-31 19:10:14</div>
<div class="right">
<div class="progress">
<div class="progress-bar progress-bar-info progress-bar-striped active" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width:86.7%"><b>13/15 (86.7%)</b>
</div>
</div>
</div>
</div>
</td>
</tr>
So you essentially have one child. Then you put your collapse within your <div> tag rather than your <tr> tag.
Hope this helps.
I'd put the swapping chevron part in the click function like this:
$('.accordion-toggle').on('click', function() {
$('.chevron_toggleable').removeClass('glyphicon-chevron-up').addClass('glyphicon-chevron-down');
$(this).find('span').closest('.chevron_toggleable').toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});
JSFiddle

Create a table inside script tag

How do I create a table inside the script tag without going to another page? I am currently using the document.write() function but it opens a new page but i want it to stay on the page as i click my button? here is my current code:
$( "#searchVehicleDesc" ).button().click(function( event ) {
document.write('<fieldset>');
document.write('<legend>Dashboard<\/legend><br>');
document.write('<table border="1" width="650">');
document.write('<tr bgcolor=#c0c0c0>');
document.write('<td width=100 align="center"><font face="helvetica"><b>Vehicle Name<\/b><\/font><\/td>');
document.write('<td width=80 align="center"><font face="helvetica"><b>Service Type<\/b><\/font><\/td>');
document.write('<td width=80 align="center"><font face="helvetica"><b>Others<\/b></\font><\/td>');
document.write('<td width=100 align="center"><font face="helvetica"><b>Reference No.<\/b><\/font><\/td>');
document.write('<td width=80 align="center"><font face="helvetica"><b>Reference Date<\/b><\/font><\/td>');
document.write('<td width=80 align="center"><font face="helvetica"><b>Reference Type<\/b><\/font><\/td>');
document.write('<\/tr>');
document.write('<\/table>');
document.write('<\/fieldset>');
});
Do something like this:
var myTable =
'<fieldset>' +
'<legend>Dashboard</legend></br>' +
'<table border="1" width="650">' +
'<tr bgcolor=#c0c0c0>' +
'<td width=100 align="center"><font face="helvetica"><b>Vehicle Name</b></font></td>' +
'<td width=80 align="center"><font face="helvetica"><b>Service Type</b></font></td>' +
'<td width=80 align="center"><font face="helvetica"><b>Others</b></font></td>' +
'<td width=100 align="center"><font face="helvetica"><b>Reference No.</b></font></td>' +
'<td width=80 align="center"><font face="helvetica"><b>Reference Date</b></font></td>' +
'<td width=80 align="center"><font face="helvetica"><b>Reference Type</b></font></td>' +
'</tr>' +
'</table>' +
'</fieldset>';
$( "#searchVehicleDesc" ).button().click(function( event ) {
$(document.body).append(myTable);
});
Notice that you don't have to escape forward slashes (/) in JavaScript strings.
You can also make the table HTML a lot shorter, while also making it easier to maintain, by using CSS:
In your JavaScript:
var myTable =
'<fieldset>' +
'<legend>Dashboard</legend></br>' +
'<table>' +
'<tr>' +
'<td class="large">Vehicle Name</td>' +
'<td class="small">Service Type</td>' +
'<td class="small">Others</td>' +
'<td class="large">Reference No.</td>' +
'<td class="small">Reference Date</td>' +
'<td class="small">Reference Type</td>' +
'</tr>' +
'</table>' +
'</fieldset>'
CSS file:
table{
border: 1px solid black;
}
table tr{ /* You could use just `tr{` here (leave out `table `), I just prefer this */
background-color: #c0c0c0;
}
table tr td{ /* Same here, for `td{` */
font-family:helvetica;
font-weight:bold;
text-align: center;
}
.large{
width: 100px;
}
.small{
width: 80px;
}
document.write() will overwrite current content in your page. You can use .append() instead:
$("#searchVehicleDesc" ).button().click(function( event ) {
$(document.body).append('<fieldset><legend>Dashboard</legend><br /><table border="1" width="650"><tr bgcolor="#c0c0c0"><td width="100" align="center"><font face="helvetica"><b>Vehicle Name</b></font></td><td width=80 align="center"><font face="helvetica"><b>Service Type</b></font></td><td width="80" align="center"><font face="helvetica"><b>Others</b></font></td><td width="100" align="center"><font face="helvetica"><b>Reference No.</b></font></td><td width="80" align="center"><font face="helvetica"><b>Reference Date</b></font></td><td width="80" align="center"><font face="helvetica"><b>Reference Type</b></font></td></tr></table></fieldset>');
});
You should create DOM elements in JS using the document.createElement() method. Read this: https://developer.mozilla.org/en-US/docs/Web/API/document.createElement
You could also append the html string like document.getElementById('target_container').innerHTML('<div><-- your über long html string--></div>');
In case of jQuery you can simply append your html string to an object, like $('#target_container').html('<div><-- your über long html string--></div>');
use jQuery's append() function.
$( "#searchVehicleDesc" ).button().click(function( event ) {
$('#searchVehicleDesc').append('<fieldset>');
});
see jsFiddle:
http://jsfiddle.net/L2DEE/
That is because each time you call document.write, you are overriding the document.
Concat all the strings and then append it to some container.
You appear to be using jQuery, there are lots of methods you can use to add content to an existing page:
html
append
appendTo
prepend
prependTo
before
insertBefore
after
insertAfter
...and others. They're all covered, with examples, in the jQuery API documentation.
Just make a div and put your table in it.
<div id="container"></div>
your script should be something like this:
var table = '<fieldset>'+
'<legend>Dashboard</legend><br>'+
'<table border="1" width="650">';
... and so on...
Then simply append to your container.
$("#container").append(table);
You can do following
var myObj, txt;
txt += "<table>"
myObj = JSON.parse(text);
for (x in myObj.issues) {
console.log(myObj.issues[x])
txt += "<tr><td>" + myObj.issues[x].key + "</td>";
txt += "<td>" + myObj.issues[x].fields.summary + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;

Categories