Loop through gridview rows on client-side javascript - javascript

I have a gridview with a template field of check boxes.
I have my rows color coded in BLUE color in the gridview based on a database value on page load.
Now I want a button on the page to loop through the gridview and select the the checkbox for the rows that are in BLUE Color without a post back.
any help would be appreciated.
thanks.

Loop through gridview rows on client-side javascript
var GridviewRows = $("#<%=gvbooksdetails.ClientID%> tr").length;
var rowlenght = GridviewRows - 1;
for (var i = 0; i < rowlenght; i++)
{
var Aname = document.getElementById("MainContent_gvbooksdetails_lblgvauthorname_" +[i]+"").innerHTML;
var Bname = document.getElementById("MainContent_gvbooksdetails_lblgvbookname_" +[i]+ "").innerHTML;
var BType = document.getElementById("MainContent_gvbooksdetails_lblgvbooktype_" +[i]+ "").innerHTML;
var Pubilication = document.getElementById("MainContent_gvbooksdetails_lblgvPublisher_" + [i] + "").innerHTML;
var Bid = document.getElementById("MainContent_gvbooksdetails_hiddenid_"+[i]+"").value;
}
Instead of foreach we can use this method.

$('#mygrid tr.blueClass input[type="checkbox"]').each(
function() {
this.checked = true;
});
Assuming mygrid is the name of your gridview, and each blue row has a class called blueClass

Related

How to get value from GridView cell with Javascript

I'm trying to get a value from a GridView cell to change the source of an embed PDF. I execute a function when a button that is placed on each row of the GridView is clicked.
This is the code I have so far:
<script>
function changepdf(pdf) {
var value = document.getElementById('<%= GridView1.ClientID %>').rows[pdf.rowIndex].cells[3].innerText;
var file = document.getElementById('pdf');
file.src = 'pdf/catalogosh.pdf#page=' + value + '&#toolbar=0&#view=fit';
return false;
}
</script>
The Javascript function works fine when I write exactly the new source like this:
<script>
function changepdf(pdf) {
var file = document.getElementById('pdf');
file.src = 'pdf/catalogosh.pdf#page=4&#toolbar=0&#view=fit';
return false;
}
</script>
The main idea is to change the PDF page taking the value from de GridView.
Thanks in advance for any help.
I've just solved it. I'm pasting the code here for anyone that's trying to solve the same problem:
function changepdf(pdf) {
var row = pdf.parentNode.parentNode;
var rowIndex = row.rowIndex;
var value = document.getElementById('<%= GridView1.ClientID %>').rows[rowIndex].cells[2].innerText;
var file = document.getElementById('pdf');
file.src = 'pdf/catalogosh.pdf#page=' + value + '&#toolbar=0&#view=fit';
return false;
}
My problem was the rowIndex. The code was bad and I was getting the wrong value.
I added this two lines to get it well:
var row = pdf.parentNode.parentNode;
var rowIndex = row.rowIndex;
And then I got the cell value with this line:
var value = document.getElementById('<%= GridView1.ClientID %>').rows[rowIndex].cells[3].innerText;

Get second, third and so on values

I have this problem here
The problem has been solved, but my question is how can I get the second value from that, or the third one. The sheet will have many tables and at some point I will need a total for each table. Also, is there any solution to automatically find the the array number which contain date row for each table (instead defining this manually). Hope my explanation make sense.
Thank you!
Kind regards,
L.E. Test file
If I understood your question correctly, instead of breaking the loop when a match to "Total" is found do whatever is needed to be done within the loop like so...
var today = toDateFormat(new Date());
var todaysColumn =
values[5].map(toDateFormat).map(Number).indexOf(+today);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1",
"dd/MM/yyyy");
for (var i=0; i<values.length; i++){
if (values[i][0]=='Total'){
nr = i;
Logger.log(nr);
var output = values[nr][todaysColumn];
// Do something with the output here I"m assuming you email it
}
}
The loop will keep going and find every "Total" and do the same thing. This answer assumes that the "Totals" are in the same column. You can get fancier with this if you only want certain tables to send and not others, but this should get you started.
I didn't quite understand the second part of your question...
"Also, is there any solution to automatically find the the array
number which contain date row for each table (instead defining this
manually). Hope my explanation make sense."
I'm guessing you want all the rows that contain "Total" in the specific column. You could instantiate a variable as an empty array like so, var totals = [];. Then instead of sending the email or whatever in the first loop you would push the row values to the array like so, totals.push(nr+1) . //adding 1 gives you the actual row number (rows count from 1 but arrays count from 0). You could then simply loop through the totals array and do whatever you wanted to do. Alternatively you could create an array of all the values instead of row numbers like totals.push(values[nr][todaysColumn]) and loop through that array. Lots of ways to solve this problem!
Ok based on our conversation below I've edited the "test" sheet and updated the code. Below are my edits
All edits have been made in your test sheet and verified working in Logger. Let me know if you have any questions.
Spreadsheet:
Added "Validation" Tab
Edited "Table" tab so the row with "Email Address" in Column A lines up with the desired lookup values (dates or categories)...this was only for the first two tables as all the others already had this criteria.
Code:
Create table/category selector...
In the editor go to File >> New >> HTMLfile
Name the file "inputHTML"
Copy and paste the following code into that file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form class="notice_form" autocomplete="off" onsubmit="formSubmit(this)" target="hidden_iframe">
<select id="tables" onchange="hideunhideCatagory(this.value)" required></select>
<p></p>
<select id="categories" style="display:none"></select>
<hr/>
<button class="submit" type="submit">Get Total</button>
</form>
<script>
window.addEventListener('load', function() {
console.log('Page is loaded');
});
</script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// The code in this function runs when the page is loaded.
$(function() {
var tableRunner = google.script.run.withSuccessHandler(buildTableList);
var catagoryRunner = google.script.run.withSuccessHandler(buildCatagoryList);
tableRunner.getTables();
catagoryRunner.getCategories();
});
function buildTableList(tables) {
var list = $('#tables');
list.empty();
list.append('<option></option>');
for (var i = 0; i < tables.length; i++) {
if(tables[i]==''){break;}
list.append('<option>' + tables[i] + '</option>');
}
}
function buildCatagoryList(categories) {
var list = $('#categories');
list.empty();
list.append('<option></option>');
for (var i = 0; i < categories.length; i++) {
if(categories[i]==''){break;}
list.append('<option>' + categories[i] + '</option>');
}
}
function hideunhideCatagory(tableValue){
var catElem = document.getElementById("categories");
if(tableValue == "Total Calls By Date" || tableValue == "Total Appointments by Date"){
catElem.style.display = "none"
document.required = false;
}else{
catElem.style.display = "block"
document.required = true;
}
}
function formSubmit(argTheFormElement) {
var table = $("select[id=tables]").val(),
catagory = $("select[id=categories]").val();
console.log(table)
google.script.run
.withSuccessHandler(google.script.host.close)
.getTotal(table,catagory);
}
</script>
</body>
<div id="hiframe" style="display:block; visibility:hidden; float:right">
<iframe name="hidden_iframe" height="0px" width="0px" ></iframe>
</div>
</html>
Edits to Code.gs file
Replace code in Code.gs with this...
//This is a simple trigger that creates the menu item in your sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Scripts Manually')
.addItem('Get Total','fncOpenMyDialog')
.addToUi();
}
//This function launches the dialog and is launched by the menu item
function fncOpenMyDialog() {
//Open a dialog
var htmlDlg = HtmlService.createHtmlOutputFromFile('inputHTML')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setWidth(200)
.setHeight(150);
SpreadsheetApp.getUi()
.showModalDialog(htmlDlg, 'Select table to get total for');
};
//main function called by clicking "Get Total" on the dialogue...variables are passed to this function from the formSubmit in the inputHTML javascript
function getTotal(table,catagory) {
function toDateFormat(date) {
try {return date.setHours(0,0,0,0);}
catch(e) {return;}
}
//get all values
var values = SpreadsheetApp
.openById("10pB0jDPG8HYolECQ3eg1lrOFjXQ6JRFwQ-llvdE2yuM")
.getSheetByName("Tables")
.getDataRange()
.getValues();
//declare/instantiate your variables
var tableHeaderRow, totalRow, tableFound = false;
//begin loop through column A in Tables Sheet
for (var i = 0; i<values.length; i++){
//test to see if values have already been found if so break the loop
if(tableFound == true){break;}
//check to see if value matches selected table
if (values[i][0]==table){
//start another loop immediately after the match row
for(var x=i+1; x<values.length; x++){
if(values[x][0] == "Email Address"){ //This header needs to consistantly denote the row that contains the headers
tableHeaderRow = x;
tableFound = true;
}else if(values[x][0] == "Total"){
totalRow = x;
break;
}
}
}
}
Logger.log("Header Row = "+tableHeaderRow)
Logger.log("Total Row = "+ totalRow)
var today = toDateFormat(new Date())
var columnToTotal;
if(catagory==''){
columnToTotal = values[tableHeaderRow].map(toDateFormat).map(Number).indexOf(+today);
}else{
columnToTotal = values[tableHeaderRow].indexOf(catagory);
}
var output = values[totalRow][columnToTotal];
Logger.log(output);
var emailDate = Utilities.formatDate(new Date(today),"GMT+1", "dd/MM/yyyy");
//here is where you would put your code to do something with the output
}
/** The functions below are used by the form to populate the selects **/
function getTables(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var tabelCol = (cSheetHeader.indexOf("Tables")+1);
var tables = cSheet.getRange(2,tabelCol,cSheet.getLastRow(),1).getValues();
return tables.filter(function (elem){
return elem != "";
});
}
function getCatagories(){
var cFile = SpreadsheetApp.getActive();
var cSheet = cFile.getSheetByName('Validation');
var cSheetHeader = cSheet.getRange(1,1,cSheet.getLastRow(),cSheet.getLastColumn()).getValues().shift();
var catagoriesCol = (cSheetHeader.indexOf("Catagory")+1);
var catagories = cSheet.getRange(2,catagoriesCol,cSheet.getLastRow(),1).getValues();
return catagories.filter(function (elem){
return elem != "";
});
}

How to get all selected child rows in DataTable

I currently quiet new in DataTable jquery .So I faced a big issue right now .I have a table that using a DataTable jquery to create a child rows.That data are get from database.
Every rows in table have a checkbox and will be submit all the selected child rows. My problem is when I want to submit the data ,it seems my code not working as I want if I changing the paginator.Thats meant ,when I select all rows in page 1 and page 2 ,there are only rows in page 2 are submitted .Please anybody help me .Below is my code for your reference. Any help will be appreciate.
All rows that are checked will be submited by click on button
$('#OthersSubmit2').on('click', function(e){
var type_of_invoice = $('#TypeInvoiceId2').val();
var program_id = $('#ProgramId2').val();
var sponsorship_id = $('#SponsorshipId2').val();
var result = [];
var data_filter = [];
data_filter = {'type_of_invoice': type_of_invoice,
'program_id':program_id,
'sponsorship_id':sponsorship_id};
var rowcollection = table.$("input:checked", {"page": "all"});
$.each($(rowcollection), function(index,rows) {
var data = $(this).parents('tr:eq(0)');
var transaction = [];
var data2 = [];
var stu_master_id = $(data).find('td:eq(0)').attr('id');
var a = $(data).parent().find('table[id='+stu_master_id+']');
console.log(a);
var sub_tbl = $(a).DataTable().$("input:checked", {"page": "all"});
$.each($(sub_tbl), function(index2,rows2) {
data2 = $(this).parents('tr:eq(0)');
var d = $(data2).find('td:eq(0)').attr('id');
transaction.push(d);
});
result.push({'stu_master_id':stu_master_id,
'transaction_id':transaction});
});
data_filter['data'] = result;
});

Using javascript Not able to disable textbox.It Immediatly enable after disabled. Can anyone give me solution?

I have One simple registration Form which is developed in C#.Net. This form also contain one Grid view which display data from database.In this,I want to disable Insert button when i select particular raw data. and i had develop this code in jquery. I used below code.
function DoStuff(lnk) {
debugger;
var grid = document.getElementById('GridView1');
var cell, row, rowIndex, cellIndex;
cell = lnk.parentNode;
row = cell.parentNode;
rowIndex = row.rowIndex;
cellIndex = cell.cellIndex;
var rowId = grid.rows[rowIndex].cells[0].textContent;
var rowname = grid.rows[rowIndex].cells[1].textContent;
var rowcontact = grid.rows[rowIndex].cells[2].innerHTML;
var rowaddress = grid.rows[rowIndex].cells[3].innerHTML;
var rowemail = grid.rows[rowIndex].cells[4].innerHTML;
var Id = document.getElementById('txt_Id');
var name = document.getElementById('txt_Name');
var contact = document.getElementById('txt_PhoneNumber');
var address = document.getElementById('txt_Address');
var email = document.getElementById('txt_EmailId');
Id.value = rowId;
name.value = rowname;
contact.value = rowcontact;
address.value = rowaddress;
email.value = rowemail;
document.getElementById('Button1').disabled = true;
};
But when i run that page it becomes disable and immediately enable automatically.....:(
Can anyone give me solution ???
You have to call this function after form is completely loaded.
Use below code to make it that happen if you are using jQuery.
$( document ).ready(function() {
DoStuff(lnk);
});

can't get the dynamic textfield value using Jquery

I can't get the dynamic textfield value. Please see the below my jquery code.
I added onclick event while creating the textfield for LandMark. Please see the below code.
I am always getting undefined. Please help me.
function dynamicEvent() {
alert("dynamic event");
$(document).ready(function(){
alert("inside ajax --> dynamic");
var table = document.getElementById("dataTable");
alert("table-->"+table);
var rowCount = table.rows.length;
alert("rowCount-->"+rowCount);
alert("value of rowCount"+rowCount);
var uniqueId;
for (var i=rowCount;rowCount>7;i++){
uniqueId = i;
alert("inside for loop");
alert("uniqueId-->"+uniqueId);
var element = document.createElement("input");
uniqueId=uniqueId-1;
element.id = "t02Travelfrom" +uniqueId;
var tfrom=element.id;
alert("tfrom id-->"+tfrom);
var t02Travelfrom=$("tfrom").val();
alert(tfrom+"--value-->" +t02Travelfrom);
}
});
}
You have incorrect selector:
var t02Travelfrom=$("tfrom").val();
change to:
var t02Travelfrom=$("#" + tfrom).val();
$("tfrom") returning elements with tag tfrom
You need $(tfrom). You don't need double quotas.

Categories

Resources