How to select Html table row using jquery - html

I am using html table. which is creating dynamically and want to select Table row if we clicked on selected row how it can be possible using jQuery. I am binding that table using AJAX call on success event.
I am getting alert message but for different row selection result will remains same. (Only first row value are displaying for every row click) ?
where i am doing mistake kindly help me
I tried Like this:
$(document).ready(function () {
$("#test").click(function () {
$('.selected').removeClass('selected');
$(this).addClass("selected");
var product = $('.p', this).html();
var infRate = $('.i', this).html();
var note = $('.n', this).html();
alert(product + ',' + infRate + ',' + note);
});
});
BINDING TABLE
function OnSuccessFunctionalGridCall(data, status) {
//d = data.GetDraftedSDDResult.ResultObject;
d = AllDataGrid;
var tbl = "<table id='lineItemTable' border='1' cellspacing='0' cellpadding='3' width='100%'>";
if ($('#tdDraftSDD').length != 0) // remove table if it exists
{ $('#tdDraftSDD').empty(); }
if (d.length == 0) {
alert('No Record to display');
}
else {
tbl += " <tr class='tr-Highlighted' style='height:30px;'><td class='align-text-center' >Sr.No</td><td class='align-text-center' style='font-weight:bold !important'>User Login</td><td class='align-text-center' style='font-weight:bold !important'>User Name</td><td class='align-text-center' style='font-weight:bold !important'>Status</td></tr>";
for (i = 0; i < d.length; i++) {
tbl += "<tr><td function='draftlineNumber' class='width4p align-text-center'>"
+ (i + 1) + "</td><td function='draftlineNumber' class='width6p'>"
+ d[i].USER_LOGIN + "</td><td class='p'>"
+ d[i].USER_NAME + "</td><td class='i'>"
+ d[i].Status; + "</td><td class='n'></tr>"
}
tbl += "</table>";
$("#tdDraftSDD").append(tbl);
return;
}
}
HTML TABLE
<tr id="trGridView">
<td>
<table border="0" cellspacing="3" cellpadding="3" class="width100p">
<tr>
<td>
<div class="ui-tabs ui-widget ui-widget-content ui-corner-all" id="tabs">
<table id="tblDraftedSDD" class="contentTable">
<tr id="displaytable">
<td>
<table id="test" class="ui-corner-all contentTable">
<tr>
<td id="tdDraftSDD" class="width100p borderTable table_new"></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
How to selected particular row can any one help me on same ?

Related

How to display a calculated value and a table when a button is clicked?

I'm tyring to display a "result table"(showing the area value and calculated time) only after a user inputs both width and height value and presse the button.
What I attempted was display input values on a sheet so the inputs are correctly passed to the function setParam().
My problems are
How to display a table only after a button is pressed.
How to set a calculated are value returned from a function to the web application.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="area">
<table>
<thead>
<tr>
<th>Area</th>
</tr>
</thead>
<tbody>
<tr>
<td>width</td>
<td><input id="width" type="number" ></input></td>
</tr>
<tr>
<td>height</td>
<td><input id="height" type="number"></input></td>
</tr>
</tbody>
</table>
</div>
<div>
<input type="button" onclick="calculateArea()" id="" value="Calcuate This!">
</div>
<div id="createdTable"></div>
<script>
function calculateArea() {
const width = document.getElementById('width').value;
const height = document.getElementById('height').value;
google.script.run.setParam(width, height);
var htmlTable = '<table id="xxx" border=1>' +
'<thead>' +
'<tr> +
'<th>Result</th> +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr>' +
'<td>Area</td>' +
'<td><input value=""><?=getArea();?></input></td>' +
'</tr>' +
'<tr>' +
'<td>Calculation Time</td>' +
'<td><input value=""></input></td>' +
'</tr>' +
'</tbody>' +
'</table>';
document.getElementById("createdTable").innerHTML = htmlTable;
}
</script>
</body>
</html>
let width = 0;
let height = 0;
let area = 0;
let time = 0;
function doGet() {
return HtmlService.createTemplateFromFile("index").evaluate();
}
function setParam(width, height) {
this.width = width;
this.height = height;
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/xxxx/edit#gid=0");
var ws = ss.getSheetByName("sheet1");
ws.getRange(1,1).setValue(width);
ws.getRange(2,1).setValue(height);
}
function getArea() {
area = width * height;
return area;
}
function getTime() {
return time;
}

Rest Api: data shows on console but html table shows undefined

My post data is being displayed on the console. But the html table shows undefined
The image below shows the problem.
My Jquery Code:
$(document).ready(function(){
//Loading all posts
var loadposts=function(){
$.ajax({
url:"http://localhost:12091/api/post/",
crossdomain: true,
method:"GET",
complete:function(xmlhttp,status){
if(xmlhttp.status==200)
{
var data=xmlhttp.responseJSON;
$("#msg").html(data[0]);
console.log(data[0]);
var str='';
for (var i = 0; i < data.length; i++) {
str += "<tr>";
str += "<td>"+data[i].UserId+"</td>";
str += "<td>"+data[i].PostId+"</td>";
str += "<td>"+data[i].Post1+"</td>";
str += "<td><button class='btn btn-danger' onclick=\"deletepost("+data[i].PostId+")\">Delete</button></td>";
str += "<td><button class='btn btn-info' onclick=\"editpost()\">Edit</button></td>";
str += "</tr>";
}
$("#show__posts tbody").html(str);
}
else
{
$("#msg").html(xmlhttp.status+":"+xmlhttp.statusText);
}
}
});
}
loadposts();
});
The html table:
<div class="container">
<p id="msg"></p>
<table class="table table-striped" border="1" id="show__posts" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>User Id</th>
<th>Post Id</th>
<th>Post</th>
<th>Delete</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
What am I doing wrong?
Probably irrelevant but i'm using asp.net web api in the backend
JavaScript doesn't have a .length property for objects. If you want to work it out, you have to use Object.keys(data).length instead.

How to export multiple HTML tables into a single excel file, along with the html table's css/style?

I know there are a lot of this type of question in this site, but i cant find any working solution for this that suit my need. What i need is
1. export multiple html table to excel
2. the table in the excel look exactly like the html table (the css, styling are the same. e.g background-color)
Is there any way to do this using javascript,etc.?
I found one question for this problem here, but the solution shown there did not solve the css problem. Means that the excel table not have the css like the html table (e.g The excel table doesnt have yellow background eventhough the html table have it)
So basically the main problem is I need the format for the excel file to be same as the html table (css,etc.). Sorry I am new to programming..
Here you can access the jsfiddle. Or if the link doesnt work, you can just try it below (The codes are taken from the original post , but with an addition of a simple yellow-colored background css in it's tr)Thanks in advance.
var tablesToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
+ '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
+ '<Styles>'
+ '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
+ '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
+ '</Styles>'
+ '{worksheets}</Workbook>'
, tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
, tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(tables, wsnames, wbname, appname) {
var ctx = "";
var workbookXML = "";
var worksheetsXML = "";
var rowsXML = "";
for (var i = 0; i < tables.length; i++) {
if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
for (var j = 0; j < tables[i].rows.length; j++) {
rowsXML += '<Row>'
for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
dataFormula = (dataFormula)?dataFormula:(appname=='Calc' && dataType=='DateTime')?dataValue:null;
ctx = { attributeStyleID: (dataStyle=='Currency' || dataStyle=='Date')?' ss:StyleID="'+dataStyle+'"':''
, nameType: (dataType=='Number' || dataType=='DateTime' || dataType=='Boolean' || dataType=='Error')?dataType:'String'
, data: (dataFormula)?'':dataValue
, attributeFormula: (dataFormula)?' ss:Formula="'+dataFormula+'"':''
};
rowsXML += format(tmplCellXML, ctx);
}
rowsXML += '</Row>'
}
ctx = {rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i};
worksheetsXML += format(tmplWorksheetXML, ctx);
rowsXML = "";
}
ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
workbookXML = format(tmplWorkbookXML, ctx);
console.log(workbookXML);
var link = document.createElement("A");
link.href = uri + base64(workbookXML);
link.download = wbname || 'Workbook.xls';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
})();
<table id="tbl1" class="table2excel">
<tr style="background-color:yellow;">
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>1
</td>
<td>2
</td>
<td>3
</td>
</tr>
<tr>
<td>Butter</td>
<td>4
</td>
<td>5
</td>
<td >6
</td>
</tr>
</table>
<hr>
<table id="tbl2" class="table2excel">
<tr>
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>7
</td>
<td>8
</td>
<td>9
</td>
</tr>
<tr>
<td>Butter</td>
<td>14
</td>
<td>15
</td>
<td >16
</td>
</tr>
</table>
<button onclick="tablesToExcel(['tbl1','tbl2'], ['ProductDay1','ProductDay2'], 'TestBook.xls', 'Excel')">Export to Excel</button>
Found the solution for this. I use the DataTables. Read more here DataTables forum

Jquery datatable plugin not loading

Datatable was not working. Even console has no errors regarding datatables. Once the page gets loaded, the datatable plugin was not even loading. I tried with cdn links too, still the plugin was not working with my script.
Below is my sample code:
$('#newtable').dataTable( {"pagingType": "full_numbers"} );
<table class="table table-bordered table-hover" id="broker" cellspacing="0">
<thead>
<tr><th class="info">Broker</th>
<th class="info">Address</th>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
</tbody>
</table>
Scripts and css added:
<script src="-/scripts/jquery.dataTables.min.js"></script>
<link href="-/styles/datatables.css" rel="stylesheet">
<link href="-/styles/datatables.responsive.css" rel="stylesheet">
<script src="-/scripts/datatables.responsive.js"></script>
Here is the exact script I have used to populate the table and map for a page:
setTimeout(function() {
$(document).ready(function() {
// Search button clicked
$('#btnSearch').click(function(e) {
e.preventDefault();
$('#searchUserLongitude').val("");
$('#searchUserLatitude').val("");
// Do an AREA search
getBrokerSearchList('AREA');
});
// Hide certain text/functions if geo-location is not available
if (window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(function(position) {
$("#findAdvisor").removeClass("hide");
$("#findAdvisorOr").removeClass("hide");
$("#findAdvisorText").removeClass("hide");
$('#searchGpsAvailable').val("Y");
}, function() {
//do nothing.
});
}
});
}, 1000);
function openInfo(agentCode, lat, lng) {
var googleMap = this.APP.instances.googleMap;
googleMap.openInfo(agentCode, lat, lng);
window.location = '#map';
}
function glSuccess(lat, lon) {
$('#searchUserLongitude').val(lon);
$('#searchUserLatitude').val(lat);
$('#searchTownStreet').val("");
$('#searchPostCode').val("");
$('#searchPostCode').trigger('render.customSelect'); // Update the dropdown
// Do a GPS search
getBrokerSearchList('GPS');
}
/*
* Function to call if the browser doesn't support geoLocation or the
* user declines to send their position
*/
function glFail() {
alert('Sorry. Either your browser does not support geoLocation, or you refused the request.');
}
// Get the fund prices
function getBrokerSearchList(typeOfSearchRequested) {
$("#advisorFinder").addClass("hidden");
$("#finalSection").addClass("invisible");
$("#messagePleaseWait").removeClass("hidden");
$("#messageError").addClass("hidden");
$("#messageNotFound").addClass("hidden");
$("#messageErrorService").addClass("hidden");
var searchTownStreet = $("#searchTownStreet").val();
var searchPostCode = $("#searchPostCode").val();
var searchUserLatitude = $("#searchUserLatitude").val();
var searchUserLongitude = $("#searchUserLongitude").val();
var searchGpsAvailable = $("#searchGpsAvailable").val();
// AJAX call to get advisor search data (JSON), and update the page based on it
$.ajax({
type: 'POST',
url: '/services/findAdvisors?searchTypeOfSearchRequested=' + encodeURIComponent(typeOfSearchRequested) + '&searchTownStreet=' + encodeURIComponent(searchTownStreet) + '&searchPostCode=' + encodeURIComponent(searchPostCode) + '&searchUserLatitude=' + encodeURIComponent(searchUserLatitude) + '&searchUserLongitude=' + encodeURIComponent(searchUserLongitude) + '&searchGpsAvailable=' + encodeURIComponent(searchGpsAvailable),
dataType: "json", //to parse string into JSON object,
success: function(data) {
if (data) {
if (data.errors) {
// We got data back from the service, but there are errors
// Show/hide the appropriate sections
$("#advisorFinder").removeClass("hidden");
$("#messagePleaseWait").addClass("hidden");
var htmlErrors = "<div class='alert alert-danger custom-alert'>";
var displayErrors = false;
// Loop over all of the errors returned and attempt to deal with each one individually
for (var prop in data.errors) {
htmlErrors = htmlErrors + "<p>" + data.errors[prop].toString() + "</p>";
displayErrors = true;
}
htmlErrors = htmlErrors + "</div>";
if (displayErrors) {
$("#messageErrorService").empty().append(htmlErrors);
$("#messageErrorService").removeClass("hidden");
}
// Tidy up the boxes
$(window).trigger('resize');
} else {
// Update the search results
var lenAdvisorList = data.findAdvisorResultList.length;
var htmlAdvisorList = "";
var protocol = "";
if (lenAdvisorList > 0) {
// We have results
// Build the HTML
htmlAdvisorList += "<div class='box-simple'>";
htmlAdvisorList += "<div class='content' style='padding:5px'>";
htmlAdvisorList += "<div class='table-wrapper' style='margin-top: 15px;'>";
htmlAdvisorList += "<table cellspacing='0' class='table table-bordered table-hover datatables' id='broker'>";
htmlAdvisorList += "";
// Add the table header
htmlAdvisorList += "<thead>";
htmlAdvisorList += "<tr>";
htmlAdvisorList += "<th class='info'>Broker</th>";
htmlAdvisorList += "<th class='info'>Address</th>";
htmlAdvisorList += "<th class='info'>Phone</th>";
htmlAdvisorList += "<th class='info'></th>";
htmlAdvisorList += "</tr>";
htmlAdvisorList += "</thead>";
// Add the table rows
for (var i = 0; i < lenAdvisorList; i++) {
if (data.findAdvisorResultList[i].agentNumber) {
htmlAdvisorList += "<tr data-unqcode=" + data.findAdvisorResultList[i].agentNumber + " data-address=" + data.findAdvisorResultList[i].address + " data-location=" + data.findAdvisorResultList[i].brokerLatitude + "," + data.findAdvisorResultList[i].brokerLongitude + ">";
htmlAdvisorList += "<td>" + data.findAdvisorResultList[i].agency + "</td>";
htmlAdvisorList += "<td>" + data.findAdvisorResultList[i].address + "</td>";
htmlAdvisorList += "<td><a href='tel:" + data.findAdvisorResultList[i].workphone + "'>" + data.findAdvisorResultList[i].workphone + "</a></td>";
htmlAdvisorList += "<td width='32'>";
htmlAdvisorList += "<a id='" + data.findAdvisorResultList[i].agentNumber + "' href='#'><img width='32' height='32' src='-/assets/elements/icon_map.png'></a>";
htmlAdvisorList += "<div class='hidden'>";
htmlAdvisorList += "<div class='info-window'>";
htmlAdvisorList += "<p><strong>" + data.findAdvisorResultList[i].agency + "</strong></p>";
htmlAdvisorList += "<p>Address: <strong>" + data.findAdvisorResultList[i].address + "</strong></p>";
htmlAdvisorList += "<p>Phone: <strong>" + data.findAdvisorResultList[i].workphone + "</strong></p>";
htmlAdvisorList += "<p>Email: <strong>" + data.findAdvisorResultList[i].email + "</strong></p>";
if (data.findAdvisorResultList[i].website != '' && data.findAdvisorResultList[i].website.substring(0, 4) != 'http') {
protocol = "http://";
} else {
protocol = "";
}
htmlAdvisorList += "<p><strong>Website:</strong> <a target='_blank' href='" + protocol + data.findAdvisorResultList[i].website + "'>" + data.findAdvisorResultList[i].website + "</a><br/></p>";
htmlAdvisorList += "</div>";
htmlAdvisorList += "</div>";
htmlAdvisorList += "</td>";
htmlAdvisorList += "</tr>";
}
}
// Clear the existing HTML for the results list
$('#resultsList').empty();
// Show the new HTML + other page updates
if (htmlAdvisorList != "") {
$("#resultsList").append(htmlAdvisorList);
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageNotFound").addClass("hidden");
// Initialise the map
// Will read the data from the table and populate the map
// Must happen before the datatables update
APP.instances.googleMap.init();
// Initialse the datatables
$('#broker').dataTable({
"pagingType": "full_numbers"
});
}
// Tidy up the boxes
$(window).trigger('resize');
} else {
// We don't have results
// Clear the existing HTML for the results list
$('#resultsList').empty();
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageNotFound").removeClass("hidden");
// Initialise the map
APP.instances.googleMap.init();
// Tidy up the boxes
$(window).trigger('resize');
}
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
// We got an error during the AJAX call
// Clear the existing HTML for the results list
$('#resultsList').empty();
$("#advisorFinder").removeClass("hidden");
$("#finalSection").removeClass("invisible");
$("#messagePleaseWait").addClass("hidden");
$("#messageError").removeClass("hidden");
$("#messageNotFound").addClass("hidden");
// Initialise the map
APP.instances.googleMap.init();
// Tidy up the boxes
$(window).trigger('resize');
}
});
}
The reason is because you're using the wrong table ID. You declared the table with "broker":
<table class="table table-bordered table-hover" id="broker" cellspacing="0">
But then instantiate the DataTable with "newtable":
$('#newtable').dataTable( {"pagingType": "full_numbers"} );
The solution is to change your line to be:
$('#broker').dataTable( {"pagingType": "full_numbers"} );
Any time you're having issues with a library not working as expected, it's usually a good idea to double check the links you're using to request the library. You'll also want to make sure your table markup is correct as well. Lastly, the table id in your html needs to be the same as the selector you use to initialize the table features in your jQuery.
The solution below resolves these issues and works. Hope this helps!
$(document).ready(function() {
$('#broker').DataTable({
"pagingType": "full_numbers"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table id="broker" class="display table table-bordered table-hover" style="width:100%" cellspacing="0">
<thead>
<tr>
<th>Broker</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td>c</td>
<td>d</td>
</tr>
<tr>
<td>e</td>
<td>f</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Broker</th>
<th>Address</th>
</tr>
</tfoot>
</table>

call razor function from javascript

I'm creating a website with razor with a database but I have a problem changing database elements from within the webpage.
All elements are shown in a table with an update button. If the button is clicked, it sends it's ID to a JavaScript function. In that function an array is created with all the necessary properties. Then I want to pass that array to my razor function, but when calling the function in JavaScript, I get an error (The name 'kamer' does not exist in the current context). Anyone knows a solution?
thanks!
my razor function:
#functions{
public String saveRoom(string[] room){
var db = Database.Open("Studentenkamers");
var sql = "UPDATE Studentkamer SET oppervlakte='" + room[1] + "', locatie='" + room[2] + "', type='" + room[3] + "', vrij='" + room[4] + "' WHERE id='" + room[0] + "'";
db.Query(sql);
return "ok";
}
}
the html and javascript code:
#foreach(var row in db.Query(getKamers))
{
<tr id="#row.id">
<td class="td-id">#row.id</td>
<td class="td-opp"><input type="text" value="#row.oppervlakte" name="oppervlakte" id="td-opp" /></td>
<td class="td-loc">#row.locatie</td>
<td class="td-type"><input type="text" value="#row.type" name="type" id="td-type" /></td>
<td class="td-kamernr">#row.kamernr</td>
<td class="td-vrij"><input type="text" value="#row.vrij" name="vrij" id="td-vrij" /></td>
<td class="td-update"><input type="button" value="opslaan" onclick="updateRoom(this.id)" name="opslaan" id="#row.id" /></td>
</tr>
}
</table>
<script type="text/javascript">
function updateRoom(id) {
var opp = $("#" + id + " .td-opp input").attr("value");
var locatie = $("#" + id + " .td-loc").html();
var type = $("#" + id + " .td-type input").attr("value");
var kamernr = $("#" + id + " .td-kamernr").html();
var vrij = $("#" + id + " .td-vrij input").attr("value");
var kamer = [id, opp, locatie, type, kamernr, vrij];
alert(kamer);
#saveRoom(kamer);
}
</script>