jquery html table in variable row count - javascript

Any idea how to count rows from a table generated by $.post . I was able to get the html code to a global variable but no success to use it as a input for row count function.
var prelaz;
$(document).ready(function(){
$("input").keyup(function(){
var brkart = $("#brk").val();
var ime = $("#im").val();
var prez = $("#pre").val();
var adres = $("#adr").val();
var tele = $("#tel").val();
$.post("getpacijent.php", {
b: brkart,
i: ime,
p: prez,
a: adres,
t: tele
}, function(data) {
$("#izlaztablica").html(data);
prelaz = data;
});
});
});
function PromenaTable() {
x = (prelaz).attr('rows').length;
document.getElementById("rowcount").innerHTML= x;
}
I call function PromenaTabele() when any of fields #brk, #im, #pre, #adr, #tel changes.

Jquery
function PromenaTable() {
var table=$("#tableId").find('tr').length; // Count Number Of Rows
var table=$("#tableId").find('tr').not(':first').length;//Count Number of Rows Excluding the 1st Row i.e Table Headings
}

Related

Passing appended text box values back to Google App Script Side

I have figured out how to append text boxes and set class as autocomplete therefore setting default values as the dynamic list generated in an avaliableTag function on the google app script side. I need to get each appended text box value back to the google app script side so the end user can submit the data and a new row of data will be appended to the google sheet. Here is my html code
<label for="units" style="font-size:125%;"><b>Number of items on Ticket</b></label>
<input type="text" name="units" id="units">
<!-- specified units by user-->
<button id = 'numitems' onclick = "getUnits()">Add items </button>
<!-- button that runs function to append appropriate # of boxes -->
</div>
<button id = 'submit' type = 'submit'name = "action">Submit </button>
Here is my google script code (left out doGet and HTML Service) these functions are what the user will submit to google sheet and the function that generates autocomplete options. Still need to get userInfo.MEDS
function userClicked(userInfo){
var ss = SpreadsheetApp.openByUrl('someURL');
var ws= ss.getSheetByName('Sheet1')
var user = Session.getActiveUser();
var timestamp = Utilities.formatDate(new Date(), 'CST', 'MM/dd/yyyy HH:mm:ss')
Logger.log(userInfo)
ws.appendRow([user,userInfo.id,userInfo.ticket,userInfo.items,userInfo.MEDS,timestamp]);
}
function getAvailableTags() {
var ss = SpreadsheetApp.openById("someId");
var s = ss.getSheetByName("someSheet");
var data= s.getRange("A2:A").getValues();
var headers = 1;
var tagColumn = 0;
var availableTags = [];
for (var row=headers; row < data.length; row++) {
availableTags.push(data[row][tagColumn]);
}
return( availableTags );
}
and finally here is the js/jquery side
var x=1
function appendRow()
{
var d = document.getElementById('left-col');
d.innerHTML += "<input type='text'class = 'autocomplete' id='tst"+ x++ +"'><br >";
}
function getUnits() {
var units = $("#units").val();
x=1
for (var count = 1; count < units; count++) {
$("<input type='text'class = 'autocomplete' id='tst"+ x++ +"'><br >").appendTo("#left-col");
}
var mednum = 0
$("#left-col").append("<input type='text'class = 'autocomplete' id='tst"+ x++ +"'>")
;
}
$(function() {
google.script.run.withSuccessHandler(buildTagList)
.getAvailableTags();
});
function buildTagList(availableTags) {
$( ".autocomplete" ).autocomplete({
source: availableTags
});
}
$('#submit').on('click', function (){
$('.autocomplete').each(function() {
var med = $(this).val();
console.log(med);
});
});
window.onload=function(){
document.getElementById('submit').addEventListener('click',buttonClick);
function buttonClick() {
var userInfo = {};
userInfo.Id = document.getElementById('ptid').value
userInfo.ticket = document.getElementById('ticket').value
userInfo.items = document.getElementById('items').value
}}
I need something that will take value of each appended box and let me store it in the userInfo object so it can be passed back to the gs side
You can use google.script.run to run a function in code.gs side and send the form object [1]. Also, you should prevent the default behavior for when the form is submitted:
function buttonClick() {
var userInfo = {};
userInfo.Id = document.getElementById('ptid').value
userInfo.ticket = document.getElementById('ticket').value
userInfo.items = document.getElementById('items').value
google.script.run.userClicked(userInfo)
}
$("#formID").submit(function(e){
e.preventDefault();
});
[1] https://developers.google.com/apps-script/guides/html/communication#forms

DataTables won't convert HTML table without an alert() beforehand

I'm building a page that makes an Ajax call to retrieve a .csv file, and load the values into an HTML table. I call it in a $(document).ready(function(){ ltm.init(); }); call at the bottom of the HTML file.
It loops over the rows of the CSV file, and constructs an HTML table in a javascript variable, then hands the table off to the DOM using $('#myTable').html(table_data). The next function, ltm.convertTableToDataTable() uses $('#myTable').DataTable() to convert it to a simple DataTable. However, it's not firing. I added a button to call the convertTableToDataTable() function, and when I click it, it works fine, and the DataTable is fully functional.
If I put an alert() in the convertTableToDataTable immediately before the $('#myTable').DataTable(), the alert displays, and the table converts properly. If I move the alert to after the .DataTable() call, the alert displays, and the table does not convert.
I've tried using setTimeout($('#myTable').DataTable(),5000); to introduce a delay before the .DataTable() call, but that doesn't work either.
How can I get this to load in the data and create a DataTable thing on my page without the alert?
Here's my genericized javascript snippet:
var ltm = {
// local variables
urlCSV: 'myData.csv',
init: function() {
ltm.loadCSVDataIntoTable();
//alert('convertTableToDataTable fired!');
ltm.convertTableToDataTable();
// Bind click events
$('#btnLoadCSVData').click(function() {
ltm.loadCSVDataIntoTable();
});
$('#btnMakeDataTable').click(function() {
ltm.convertTableToDataTable();
});
},
loadCSVDataIntoTable: function() {
// The URL contains the .csv file. The first row of the file is the column headers.
$.ajax({
url:ltm.urlCSV,
dataType:"text",
success:function(csvData) {
var my_data = csvData.split(/\r?\n|\r/);
// var table_start = '<table class="table table-bordered table-striped" id="tblLTMStrains">';
var table_start = '<table class="display" id="tblLTMStrains">';
var table_end = '</table>';
var table_head_start = '<thead><tr>';
var table_head_end = '</tr></thead>';
var table_head = '';
var table_foot_start = '<tfoot><tr>';
var table_foot_end = '</tr></tfoot>';
var table_body_start = '<tbody>';
var table_body_end = '</tbody>';
var table_rows = '';
var table_data = '';
for(var intRow = 0; intRow<my_data.length; intRow++)
{
if (intRow===0) { // First row contains column headers
var cell_data = my_data[intRow].split(",");
for(var cell_intRow=0; cell_intRow<cell_data.length; cell_intRow++)
{
table_head += '<th>'+cell_data[cell_intRow]+'</th>';
}
} else {
if (my_data[intRow].length > 0) { // Gracefully handle null lines
var cell_data = my_data[intRow].split(",");
var blnLoadRow = true;
if ([Some conditions under which I want to filter out the row]) {
blnLoadRow = false;
}
if (blnLoadRow){
var thisRow = $('#templateDataRow').html();
// Can't put the <tr> content in a DIV without it stripping out all the tags
// Also, even if I don't put a <tbody> in, the DOM will create one anyway, so strip it out too.
thisRow = thisRow.replace("<table>","");
thisRow = thisRow.replace("<tbody>","");
thisRow = thisRow.replace("</tbody>","");
thisRow = thisRow.replace("</table>","");
thisRow = thisRow.replace("__MYFIELD0__",cell_data[0]);
thisRow = thisRow.replace("__MYFIELD1__",cell_data[1]);
thisRow = thisRow.replace("__MYFIELD2__",cell_data[2]);
thisRow = thisRow.replace("__MYFIELD3__",cell_data[3]);
thisRow = thisRow.replace("__MYFIELD4__",cell_data[4]);
table_rows += thisRow;
}
}
}
}
table_data = table_start;
table_data += table_head_start + table_head + table_head_end;
table_data += table_foot_start + table_head + table_foot_end;
table_data += table_body_start + table_rows + table_body_end;
table_data += table_end;
$('#divMyTable').html(table_data);
}
});
},
convertTableToDataTable: function() {
//alert('convertTableToDataTable fired - BEFORE!');
$('#myTable').DataTable();
//alert('convertTableToDataTable fired! - AFTER');
},
lastFunction: function() {} // all previous closing curly braces should have a comma after them
} // end of the ltm object.
change
$('#divMyTable').html(table_data);
to
$('#divMyTable').html(table_data).onload().DataTable();
this will make sure, DataTable is fired when html is loaded.
and remove the
convertTableToDataTable: function() {
//alert('convertTableToDataTable fired - BEFORE!');
$('#myTable').DataTable();
//alert('convertTableToDataTable fired! - AFTER');
},

How can I get data of selected table rows?

I am using the following snippet and from this I can find the index of a row which one is selected on the basis of checkbox on every row of the table.How can I modify this snippet so that I can get the selected row data instead of index?
Please Help!!
<script>
function myfunction3() {
var element_table = document.getElementsByName('collection');
var element_tableRows = element_table[0].rows;
var selectedTr = new Array();
var data = "";
for (var i = 0; i < element_tableRows.length; i++) {
var checkerbox = element_tableRows[i].cells[0].firstChild;
if (checkerbox.checked) {
data = data+ element_tableRows[i].getAttribute("name");
}
}
var element_paragraph = document.getElementsByName('description');
element_paragraph.innerHTML = data;
alert(data);
}
</script>
as TJ says, i dont see any index in your code. but try something like this which is cleaner
$('.collection tr').each(function () {
//processing this row
$(this).find('td input:checked').each(function () {
// there is checkbox and it is checked, do your business with it
var value_of_checkbox = $(this).val(); // which is 'data' that you wanted
});
});

JSF Extended Datatable Sorting and Filtering

I have a extended datatable, RICHFACES 3.3.3 with sorting and filtering enabled. The table is rendered dynamically. Based on the requirement, I need to disable certain rows(which contain editable fields) when the table is displayed.
I have that logic written in a Javascript function rowBlur(), and call it whenever the page is displayed. Hence, when the table is loaded the required rows are disabled as expected. The problem is whenever I filter/sort the table, the disabled rows get enabled again.
Is there any way I can call the javascript function whenever filter or sort happens?
Here is the code:
HtmlExtendedDataTable dynamicDataTable = new HtmlExtendedDataTable();
dynamicDataTable.setOnkeydown("filterAllOnEnter(event)");
function filterAllOnEnter(event) {
if(event.keyCode == 13) {
jQuery(".rich-filter-input").blur();
rowblur();
return false;
} else
return true;
}
// js code////////////
<script>
function show(){
val = '${myController.mergeWorkMap}';
}
</script>
<script>
function rowblur(){
for(var i=0;i<7;i++){
var firstCol = "myForm:dynamicTable:"+i+":col0" ;
var secondCol = "myForm:dynamicTable:"+i+":col1" ;
var merge =document.getElementById(firstCol).textContent;
var work =document.getElementById(secondCol).textContent;
var obj = JSON.parse(val).mergeWorkMap;
if(!(work == obj[merge])){
var col3 = "myForm:dynamicTable:" + i + ":col3";
var col4 = "myForm:dynamicTable:" + i + ":col4";
var col5 = "myForm:dynamicTable:" + i + ":col5";
var col6 = "myForm:dynamicTable:" + i + ":col6";
document.getElementById(col3).disabled = true;
document.getElementById(col4).disabled = true;
document.getElementById(col5).disabled = true;
document.getElementById(col6).disabled = true;
}
}
}
</script>
The rowblur() won't work properly on filtering, and on sorting the columns it won't work at all.

How to submit all grid values to the server at once with jQuery Datatables?

I looking to save all data from my grid to a server. I'm using jquery Datatables plugin.
function fnSave() {
var aTrs = oTable.fnGetNodes();
var aReturn = new Array();
for(var i=0;i<aTrs.length;i++) {
var aData=oTable.fnGetData(i);
aReturn.push( aData );
}
console.log(aReturn);
}
As return I get :
"<input name="regimentNameAgents" value="" id="regimentNameAgents" type="text">"
...
I would like to only return grid values (and not HTML).
By using this function, my value is always: value="", even if I add text in the input, why?
Is there a better way to extract all grid data ?
The data that's stored in the JDataTable isn't what's currently in the DOM, it's what you set it with originally. So when you update an input, the DOM element is updated, but there's no hook to update the data held in the jdatatable. I'd build the grid something more like this:
var grid = new Array();
$("table tr").each(function() {
var nextRow = new Array();
grid.push(nextRow);
$("td", this).each(function() {
var nextValue = $("input", this).val();
nextRow.push(nextValue);
});
});
The grid variable should then be storing your full table of data. I'm making a few assumptions about how you've structured your table there, since it wasn't posted, but I'm guessing that's fairly close to what you've got.
By using Datatables fnGetNodes, here is the solution :
function fnSave() {
var aTrs = oTable.fnGetNodes();
var aReturn = new Array();
$(aTrs).each(function() {
var nextRow = new Array();
aReturn.push( nextRow );
$("td", this).each(function() {
var nextValue = $("input", this).val();
nextRow.push(nextValue);
});
});
console.log(aReturn);
}

Categories