i need to search the html document for <p class="content"> text here </p>
and then output the full node path (CSS or XPATH)
for isntance
html > body > div class ="something" > table > tr > p class="content"
i tried with nokogiri but it doesn't handle the class and other attributes well..
i need a parser that does this without problem.
Ok try this:
var path = [];
var el = document.getElementById('myNode');
do {
path.unshift(el.nodeName + (el.className ? ' class="' + el.className + '"' : ''));
} while ((el.nodeName.toLowerCase() != 'html') && (el = el.parentNode));
alert(path.join(" > "));
Related
With the below code my goal is to extract a sheet from the Google sheet file in CSV format. However, when I want to convert the , to ; the following error message appears:
r.join is not a function
Could you please help me to solve this problem.
Also, do you think it is possible to download this new file directly to the desktop of the computer ?
function sheetToCsv(){
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "Int_Module";
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var newfile = [result].map(r => r.join(";")).join("\n");
newfile.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
}
I understand that there is 2 questions ... how to produce CSV file with semi-colon, and how to download the file directly to your PC.
1- To produce the csv content, try
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
2- To download, you will have to go through an html page.
Try this for both needs
function downloadMyCSVFile() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
var html = HtmlService.createHtmlOutput(`
<html><body onload="document.getElementById('dwn-btn').click()">
<textarea id="text-val" rows="10" style="display:none;">${content}</textarea>
<input type="button" id="dwn-btn" value="Download text file" style="display:none;"/>
<script>
window.close = function(){window.setTimeout(function(){google.script.host.close()},100)}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function(){
var text = document.getElementById("text-val").value;
var filename = "${sh.getName()}.csv";
download(filename, text);
close();
}, false);
</script>
</body></html>
`)
.setWidth(250).setHeight(100);
SpreadsheetApp.getUi().showModalDialog(html, "Downloading ...");
}
I am trying to establish a connection between JSP and Postgres. Unfortunately I only see the table with its columnms, the columnms are not filled. How can I put data into the columns?
My code:
<%# page contentType="text/html; charset=iso-8859-1" language="java"
import="java.sql.* "%>
<%# page import="java.io.*"%>
<html>
<head>
<title>Films Example: JSP</title>
</head>
<body bgcolor="white">
<div>
<h1>Filmworld</h1>
<table border=1>
<tr>
<td>imdbID</td>
<td>name</td>
<td>year</td>
<td>rating</td>
<td>votes</td>
<td>runtime</td>
<td>actors</td>
<td>genres</td>
<td>directors</td>
</tr>
<%
try {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://localhost:5432/movie";
String username = "postgres";
String password = "cemcan";
String myDataField = null;
String myQuery = "SELECT * FROM movie";
Connection myConnection = null;
PreparedStatement myPreparedStatement = null;
ResultSet myResultSet = null;
Class.forName(driver).newInstance();
myConnection = DriverManager.getConnection(url, username, password);
myPreparedStatement = myConnection.prepareStatement(myQuery);
myResultSet = myPreparedStatement.executeQuery();
out.println("<table border=1>");
while (myResultSet.next()) {
String imdbID = myResultSet.getString("imdbID");
String name = myResultSet.getString("name");
int year = myResultSet.getInt("year");
double rating = myResultSet.getDouble("rating");
int votes = myResultSet.getInt("votes");
int runtime = myResultSet.getInt("runtime");
String directors = myResultSet.getString("directors");
out.println("<tr><td>" + imdbID + "</td><td>" + name + "</td><td>" + year + "</td><td>" + rating
+ "</td><td>" + votes + "</td> <td>" + runtime + "</td> <td>" + directors + "</td> </tr>");
}
out.println("</table>");
myConnection.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException ex) {
out.print("SQLException: " + ex.getMessage());
out.print("SQLState: " + ex.getSQLState());
out.print("VendorError: " + ex.getErrorCode());
}
%>
</table>
</div>
</body>
</html>
your code has at least two problems:
if you don't have the jdbc driver in the classpath the error goes
into the application server output since you have a line with
e.printStackTrace();. you can check if this is the case because in
the html generated by jsp you did not see the html <table
border=1>
the html is not correct you are putting a table element just after
a .. element. the elements taken ffrom the db do not need
an extra tables, thar are already rows. Using a tbody is more
appropriate
I see that this is an example and it's ok for learning, but in "production code" put the login on the server side (servlet, framework controller, etc) and use at least <%=... %> in jsp instead of out, it helps to separate page markup to program variables
this script works in jQuery 1.9, but does not work in 1.8. How to convert this script to jQuery 1.8 ?
NOT Working Demo on jsfiddle
Working Demo on jsfiddle
HTML
<div id="container">
<div id="c1" class="aaa" style="text-align:right; color:red top:100px; ">child 1</div>
<div id="c2" class="aaa" style="text-align:left; top:200px; ">child 2</div>
</div>
jQuery script
$("#container").children().each( function () {
alert("element ID = " + $(this).attr('id'));
var styleProps = $(this).css(["width",
"height",
"color",
"background-color",
"text-align",
"left",
"top",
"right",
"bottom"]);
$.each(styleProps, function (prop, value) {
alert(prop + " = " + value);
});
});
The css function accepting an array wasn't implemented until 1.9.
You'll probably have to do it by hand if you're using 1.8 (loop through the values one at a time).
var styleNames = ["width", "height", "color", ...etc... ];
var i;
var $elem = jQuery(this);
for (i = 0; i < styleNames.length; ++i) {
alert(styleNames[i] + " = " + $elem.css(styleNames[i]));
}
I want to Google Adsense script output code (HTML code)
I don't mean the javascript code (which google provides to users). The HTML output (you can grab it with Firebug or Google Developer Toolbar)
Thanks.
The I frame is :
<iframe width="120" scrolling="no" height="600" frameborder="0" vspace="0" style="left:0;position:absolute;top:0" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-7051474033111975&output=html&h=600&slotname=1193041517&w=120&lmt=1339606481&flash=11.2.202&url=file%3A%2F%2F%2FC%3A%2FDocuments%2520and%2520Settings%2FLEFTERIS%2FDesktop%2Fgoogle.htm&dt=1339608015911&bpp=4&shv=r20120606&jsv=r20110914&correlator=1339608016097&frm=20&adk=1708676694&ga_vid=904765143.1337074819&ga_sid=1339608016&ga_hid=1901222006&ga_fc=1&u_tz=180&u_his=1&u_java=1&u_h=1024&u_w=1280&u_ah=934&u_aw=1280&u_cd=24&u_nplug=20&u_nmime=76&dff=serif&dfs=16&adx=8&ady=8&biw=1244&bih=293&oid=3&fu=0&ifi=1&dtd=235&xpc=dCXR5D0l2L&p=file%3A//" name="google_ads_frame1" marginwidth="0" marginheight="0" id="google_ads_frame1" hspace="0" allowtransparency="true"></iframe>
<style>a{color:#0000ff}body,table,div,ul,li{margin:0;padding:0}</style>
<script>(function(){window.ss=function(d,e){window.status=d;var c=document.getElementById(e);if(c){var a;a=c.href;var b=a.match("^(.*)([?|&]nm=)([^&]*)(.*)$");b?(b[3]=""+((Number(b[3])||0)+1),b[0]="",a=b.join("")):a+="&nm=1";c.href=a}return!0};})();function su(id) {var a = document.getElementById(id);var b = (new Date()).getTime();if (a && a.myt && b) {var t = b - a.myt;var bi = a.href.indexOf("&clkt=");if (bi > 0) {var c = a.href.substring(0, bi+6); var d = a.href.substring(bi+6, a.href.length);var ei = d.indexOf("&");var r = '';if (ei >= 0)r = d.substring(ei, d.length);a.href = c + t + r; } else {a.href += "&clkt=" + t;}}return true;}(function(){var e=function(b,a,c){var d="&"+a+"=",a=b.indexOf(d);0>a?c=b+d+c:(a+=d.length,d=b.indexOf("&",a),c=0<=d?b.substring(0,a)+c+b.substring(d):b.substring(0,a)+c);return 2E3<c.length?b:c};var f=null,g=function(b){f=b};document.addEventListener&&document.addEventListener("mousedown",g,!0);window.xy=function(b,a,c){c=c||a;if((b=b||f)&&a&&c){var d=Math.round(b.clientY-c.offsetTop);a.href=e(a.href,"nx",Math.round(b.clientX-c.offsetLeft));a.href=e(a.href,"ny",d)}};})();function cs(){window.status='';} function jcc(a) {pha=document.getElementById(a); nc=pha.href.indexOf('&jca='); if(nc>=1) return; jca=(717)+(6720)-(441); if (a=='aw0') {jca+=(-4392);} else if (a=='aw1') {jca+=(1043);} else if (a=='aw2') {jca+=(2446);} else if (a=='aw3') {jca+=(-4751);} else {jca=0;} phb=pha.href+'&jca='+jca; pha.href=phb;} function st(id) {var a = document.getElementById(id);if (a) {a.myt = (new Date()).getTime();xy(window.event, a);}return true;}function ha(a){ var pha=document.getElementById(a);var nhi=pha.href.indexOf("&nh=");if(nhi < 1) {pha.href+="&nh=1";}su(a); jcc(a); }function ca(a) { var pha=document.getElementById(a);var nci=pha.href.indexOf("&nc=");if(nci < 1) {pha.href+="&nc=1";}su(a); jcc(a); top.location.href=document.getElementById(a).href;}function ga(o,e) {if (document.getElementById) {a=o.id.substring(1);p="";r="";g=e.target;if (g) {t=g.id;f=g.parentNode;if (f) {p=f.id;h=f.parentNode;if (h)r=h.id;}} else {h=e.srcElement;f=h.parentNode;if (f)p=f.id;t=h.id;}if (t==a||p==a||r==a)return true;var pha=document.getElementById(a);var nbi=pha.href.indexOf("&nb=");if(nbi < 1) {pha.href+="&nb=1";}su(a); jcc(a); top.location.href=document.getElementById(a).href;}}</script>
<a title="www.gfi.com/fax" target="_top" onmouseover="return ss('','aw0')" onmousedown="st('aw0')" onfocus="ss('','aw0')" onclick="ha('aw0')" id="aw0" href="/aclk?sa=l&ai=BnKD-aMvYT-vyI6qU0AW52p2hB7aAuLECxuLcvRjAjbcBsOMtEAEYASDg8JsKKAQ4AFD85ObkAmCtytiDvAygAYqXwv8DugEKMTIweDYwMF9hc8gBAdoBQWZpbGU6Ly8vQzovRG9jdW1lbnRzJTIwYW5kJTIwU2V0dGluZ3MvTEVGVEVSSVMvRGVza3RvcC9nb29nbGUuaHRtgAIByALW54UYqAMByAMf6AP2COgD5QP1AwAAAMT1AwAAQBA&num=1&sig=AOD64_3Jznh97UCO3fRznTsPK1OHiH354Q&client=ca-pub-7051474033111975&adurl=http://landfax.gfi.com/fax-server-exchange-sm/%3Fadv%3D69%26loc%3D618" class="adt"><span>Send fax from computers</span></a>
<a target="_blank" href="http://www.google.com/url?ct=abg&q=https://www.google.com/adsense/support/bin/request.py%3Fcontact%3Dabg_afc%26url%3Dfile:///C:/Documents%252520and%252520Settings/LEFTERIS/Desktop/google.htm%26hl%3Den%26client%3Dca-pub-7051474033111975%26adU%3Dwww.gfi.com/fax%26adT%3DSend%2Bfax%2Bfrom%2Bcomputers%26adU%3Dwww.tradestead.com/ElectricGadgets%26adT%3DBuy%2BElectronic%2BGadgets%26adU%3Dwww.cloudsolutions.co.uk%26adT%3DGoogle%2BMigration%2BTool%26adU%3DAllwaySync.com%26adT%3DSkyDrive%2BPC%2Bsync%2Bsoftware%26gl%3DGR&usg=AFQjCNGOinsMYeIWqJU_FmQly3Uc-yRscA"><img height="16" border="0" src="http://pagead2.googlesyndication.com/pagead/abglogo/adc-en-100c-000000.png" alt="AdChoices"></a>
Probably that is what you want...
I'm adding new rows dynamically to the existing table, the first column of the table holds the Edit & Delete buttons. I'm facing 2 problems with this:
Not able to Edit and Delete newly added rows, tried .live but couldn't make it work
Not able to get the record id of the newly added rows (ajax returns the record when new rows are added).
Code looks like this:
Adding new rows:
<script type="text/javascript">
$(function() {
$('#btnSubmit').click(function() {
var oEmployee = new Object();
oEmployee.Title = $("#Title").val();
oEmployee.Middlename = $("#MiddleName").val();
oEmployee.Lastname = $("#LastName").val();
oEmployee.Email = $("#Email").val();
var DTO = {'employee': oEmployee};
var options = {
type: "POST",
url: "WebService.asmx/InsertEmployee",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response.d != "") {
if (parseInt(response.d) >= 1) {
var contactID;
contactID = parseInt(response.d);
$('#tblEmployee tbody tr:first').after("<tr id=" + contactID + "><td><input type='button' class='newContactID' value='Edit'/> <input type='button' value='Delete'/></td><td align=center>" + contactID + "</td><td align=center>" + oEmployee.Title + "</td><td align=center>" + oEmployee.Middlename + "</td><td align=center>" + oEmployee.Lastname + "</td><td align=center>" + oEmployee.Email + "</td><tr>"); // need to hook up editing and deleting function to the newly added rows }
else {
alert("Insert Failed \n" + response.d);
}
}
}
};
//Call the webservice
$.ajax(options);
});
});
</script>
Code for editing and deleting:
$(function() {
$("#tblEmployee > tbody > tr ").each(function() {
var TRID = $(this).attr("id");
$(this).find("td:first > input[value=Edit]").click(function() {
ResetOtherRowEdit();
ChangeTableCellToTextbox(TRID);
$(this).hide();
$("#tblEmployee > tbody > tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
return false;
});
$(this).find("td:first > input[value=Update]").click(function() {
UpdateRow(TRID);
});
$(this).find("td:first > input[value=Delete]").click(function() {
DeleteRow(TRID);
});
$(this).find("td:first > input[value=Cancel]").click(function() {
CancelEdit(TRID);
});
});
});
What is the best way to approach this? Editing and deleting of records work fine when they're pulled off the database.
Update
This is how the code looks like now, just began dabbling with Jquery a month back, still trying to get my head around it.
$(function() {
$("#tblEmployee > tbody > tr ").live('click', function(e) {
var TRID = $(this).attr("id");
var $target = $(e.target);
if ($target.is('#btnEdit')) {
$(this).find("td:first > input[value=Edit]").click(function() {
ResetOtherRowEdit();
ChangeTableCellToTextbox(TRID);
$(this).hide();
$("#tblEmployee > tbody > tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
return false;
});
}
else if ($target.is('#btnUpdate')) {
$(this).find("td:first > input[value=Update]").click(function() {
UpdateRow(TRID);
});
}
else if ($target.is('#btnCancel')) {
$(this).find("td:first > input[value=Cancel]").click(function() {
CancelEdit(TRID);
});
}
else if ($target.is('#btnDelete')) {
$(this).find("td:first > input[value=Delete]").click(function() {
DeleteRow(TRID);
});
}
});
});
HTML codes looks like this:
<ItemTemplate>
<tr id='<%# Eval("ContactID") %>'>
<td width="10%">
<input type="button" value="Edit" id="btnEdit"/>
<input type="button" value="Delete" id="btnDelete"/>
<input type="button" value="Update" style="display:none" id="btnUpdate" />
<input type="button" value="Cancel" style="display:none" id="btnCancel"/>
</td>
<td width="10%" align="center"><%# Eval("ContactID")%></td>
<td width="20%" align="center"><%# Eval("Title")%></td>
<td width="20%" align="center"><%# Eval("MiddleName")%></td>
<td width="20%" align="center"><%# Eval("LastName")%></td>
<td width="20%" align="center"><%# Eval("EmailAddress")%></td>
</tr>
</ItemTemplate>
You could take advantage of DOM traversal and .live() to make this work. Add a listener using .live() to the rows of the table. Inside this method, determine which element was clicked (e.currentTarget). You can use a simple conditional to check if it was a button that needs to react. Then, use DOM traversal to nail down what you want to have happen. For example, if e.currentTarget is the delete button, the you can use $(this).closest('tr').remove(); to delete the row. If you need to interact with the data through ajax, make your ajax function support passing in whatever valus you'd need (id) to perform the delete. In order to obtain the id, you'll need to get it from the ajax call and put it somewhere inside the DOM so you can retrieve it when you need it. You can always toss in a 'title' attribute when the tr is generated.
Here is a same script with php
http://www.amitpatil.me/add-edit-delete-rows-dynamically-using-jquery-php/
// Add new record
$(document).on("click","."+editbutton,function(){
var id = $(this).attr("id");
if(id && editing == 0 && tdediting == 0){
// hide editing row, for the time being
$("."+table+" tr:last-child").fadeOut("fast");
var html;
html += "<td>"+$("."+table+" tr[id="+id+"] td:first-child").html()+"</td>";
for(i=0;i<columns.length;i++){
// fetch value inside the TD and place as VALUE in input field
var val = $(document).find("."+table+" tr[id="+id+"] td[class='"+columns[i]+"']").html();
input = createInput(i,val);
html +='<td>'+input+'</td>';
}
html += '<td><img src="'+updateImage+'"> <img src="'+cancelImage+'"></td>';
// Before replacing the TR contents, make a copy so when user clicks on
trcopy = $("."+table+" tr[id="+id+"]").html();
$("."+table+" tr[id="+id+"]").html(html);
// set editing flag
editing = 1;
}
});