Php how set data in string using html id - javascript

I have long html text. Pass it from js to php. I need change ID content with my text.
I tried did it like this:
$html = new DOMDocument();
$html->loadHTML($codeText);
$html->getElementById('second_head')->nodeValue = $leadAddressTemplate;
$html->getElementById('rechnung_div')->nodeValue = $rehnungTemplate;
$res = $html->saveHTML();
It works but have problem - my <> chars system replaces to < and > and system adds <html><body> to my text.
How can I fix it? Maybe there are some flags for it?
For example, input is :
<tr>
<td colspan="2" class="invoice-products" width="100%">
<div id="rechnung_div"></div>
</td>
</tr>
And it try do it:
$html->getElementById('rechnung_div')->nodeValue = '<p>It is rechnung</p>';
As result i have this:
<tr>
<td colspan="2" class="invoice-products" width="100%">
<div id="rechnung_div"><p>It is rechnung</p></div>
</td>
</tr>
Now I can set for example element:
$appended = $html->createElement('p', 'It is rechnung');
$html->getElementById('rechnung_div')->nodeValue = '';
$rechnung_div->appendChild($appended);
But how insert table , for example like this?
<table>
<tbody><tr>
<td style="width: 40%;vertical-align: baseline;"><h1 id="invoice_type">Rechnung</h1>
<p id="invoice_title">gtrgtrgrtgtr</p></td>
<td style="width: 60%;text-align: right;vertical-align: bottom;"><h1> </h1><p id="invoice_nummer"></p></td>
</tr>
</tbody>
</table>
I can't do it with appendChild() function

Rolling together the notes from the comments:
$parent = <<<_E_
<tr>
<td colspan="2" class="invoice-products" width="100%">
<div id="rechnung_div"></div>
</td>
</tr>
_E_;
$template = <<<_E_
<p>I am a template</p>
_E_;
$temp = new DOMDocument();
$temp->loadHTML($template, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// get the document's root element
$temp_root = $temp->documentElement;
$html = new DOMDocument();
$html->loadHTML($parent, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// import the template into the current document
$node = $html->importNode($temp_root, true);
$html->getElementById('rechnung_div')->appendChild($node);
echo $html->saveHTML();
Output:
<tr>
<td colspan="2" class="invoice-products" width="100%">
<div id="rechnung_div"><p>I am a template</p></div>
</td>
</tr>

Related

For each loop to retrieve multiple messages in page

For a Chrome plugin, I need to retrieve messages. These messages are supplied to me through an html variable.
There are 2 messages in the example provided below and they both start with: <tr bgcolor="#FFFFFF"> and end with: </tr>
I retrieved the first message data, but now I need to make it so that it retrieves all the data from each of those <tr bgcolor="#FFFFFF"> </tr> messages.
What I get provided:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" type="text/css" href="xxx">
<title>Untitled</title>
</head>
<body class="bodySinScrollHor">
<table width="95%" align="center">
<tr>
<td class="etiquetaIzquierda" colspan=6>
<a class="etiquetaIzquierda"><img border=0 height=15 src="xxx"> Comunicaciones (2)</a>
</td>
</td>
</tr>
<tr>
<td colspan=6>
<hr size=1 width="100%">
</td>
</tr>
<tr id="comunicaciones">
<td colspan=6>
<table width="100%" border=0 bordercolor="#000000" cellspacing=0 cellpadding=0>
<tr bgcolor="#FFFFFF">
<td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td>
<td width="9%" class="valorCampoSinTamFijoPeque">13:22</td>
<td width="4%" align=left class="valorcampoSinTamFijoPeque">
<img src="xxx" title=" Out">
</td>
<td width="11%" class="valorCampoSinTamFijoPeque" valign=top>
<font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font>
</td>
<td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td>
<!-- <td width="61%"class="valorCampoSinTamFijoPeque">message text here</td> -->
</tr>
<tr bgcolor="#FFFFFF">
<td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td>
<td width="9%" class="valorCampoSinTamFijoPeque">13:21</td>
<td width="4%" align=left class="valorcampoSinTamFijoPeque">
<img src="xxx" title=" Out">
</td>
<td width="11%" class="valorCampoSinTamFijoPeque" valign=top>
<font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font>
</td>
<td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td>
<!-- <td width="61%"class="valorCampoSinTamFijoPeque">Message Text Here</td> -->
</tr>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Below is the code I run to retrieve the data from the first message. Note that there are 2 messages in this case, but there are people that have 54 messages so it needs to loop that many times. This part of the code:
var count = (html1.match(/<tr bgcolor="#FFFFFF">/g) || []).length;
console.log(count);
Is what provides that number for me.
matches[0].forEach(function(match, index) {
var cleintcode = /<div\s*class="t_seg_codCliente">(.*?)<\/div>/.exec(match)[1];
var cleintname = /<div\s*class="t_seg_nomCliente">(.*?)<\/div>/.exec(match)[1];
var taxId = /<div\s*class="t_seg_nifCliente">(.*?)<\/div>/.exec(match)[1];
var date = /<div\s*class="t_seg_fechaPresCliente">(.*?)<\/div>/.exec(match)[1];
var state = /<div\s*class="t_seg_estadoCliente">(.*?)<\/div>/.exec(match)[1];
var expirydate = /<div\s*class="t_seg_fechaCadCliente">(.*?)<\/div>/.exec(match)[1];
var communications = /<div\s*class="t_seg_comCliente"><a .*;">(.*?)<\/a>/.exec(match)[1];
var comclient = /<div\s*class="t_seg_comCliente"><a href="javaScript:popupComs\('(.*?)'/.exec(match)[1];
var messages = "xxx" + comclient;
var html1 = httpGet(messages);
//console.log(html1);
const cleanupDocString = html1.replace(/(?:<!--|-->)/gm, '');
parser = new DOMParser();
htmlDoc = parser.parseFromString(cleanupDocString, "text/html");
//console.log(htmlDoc);
var communicationsvalue = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[0].textContent;
if (communicationsvalue.indexOf('No existen comunicaciones asociadas a este cliente.') !== -1) {
console.log("This chat does not contain any communiction!");
} else {
//Get count of regex matches. (amount of messages)
var count = (html1.match(/<tr bgcolor="#FFFFFF">/g) || []).length;
console.log(count);
var comDate = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[0].textContent;
var comTime = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[1].textContent;
var comType = htmlDoc.getElementsByTagName('img')[1].src;
var comClient = htmlDoc.getElementsByTagName('a')[1].textContent;
var comSubject = htmlDoc.getElementsByClassName("valorCampoSinTamFijoPeque")[6].textContent;
const element = htmlDoc.getElementsByClassName('valorCampoSinTamFijoPeque')[7];
var pulledMessage = element.innerHTML;
var messageData = [{
clientCode: cleintcode,
clientName: cleintname,
taxID: taxId,
cleintDate: date,
cleintState: state,
cleintExpirydate: expirydate
},
{
mesDate: comDate,
mesTime: comTime,
mesType: comType,
mesClient: comClient,
mesSubject: comSubject,
mesText: pulledMessage
}
];
console.log(messageData);
}
});
The code above gives me this console log:
1. 0:
1. cleintDate:"31/08/17"
2. cleintExpirydate:"29/11/17"
3. cleintState:"Subject"
4. clientCode:"xxxxxx"
5. clientName:"clientName"
6. taxID:""
7. __proto__:Object
2. 1:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
Note that array 0 should not change because these messages are from the same person. I just need to grab the second message as well. So I technically need a second array like array 1 containing the data from the second message.
Wanted result:
1. 0:
1. cleintDate:"31/08/17"
2. cleintExpirydate:"29/11/17"
3. cleintState:"Subject"
4. clientCode:"xxxxxx"
5. clientName:"clientName"
6. taxID:""
7. __proto__:Object
2. 1:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
3. 3:
1. mesClient:"ClientName"
2. mesDate:"2017-08-31T00:00:00"
3. mesSubject:"Subject "
4. mesText:"Message text Here"
5. mesTime:"13:22"
6. mesType:"link"
7. __proto__:Object
I know I have to build a for loop, but I have no idea on how do this, so it looks for the second <tr bgcolor="#FFFFFF"> </tr> after the first.
Content is slightly edited to hide personal information.
You may possibly do as follows;
var data = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <link rel="STYLESHEET" type="text/css" href="xxx"> <title>Untitled</title> </head> <body class="bodySinScrollHor"> <table width="95%" align="center"> <tr> <td class="etiquetaIzquierda" colspan=6> <a class="etiquetaIzquierda"><img border=0 height=15 src="xxx"> Comunicaciones (2)</a> </td> </td> </tr> <tr> <td colspan=6> <hr size=1 width="100%"> </td> </tr> <tr id="comunicaciones"> <td colspan=6> <table width="100%" border=0 bordercolor="#000000" cellspacing=0 cellpadding=0> <tr bgcolor="#FFFFFF"> <td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td> <td width="9%" class="valorCampoSinTamFijoPeque">13:22</td> <td width="4%" align=left class="valorcampoSinTamFijoPeque"> <img src="xxx" title=" Out"> </td> <td width="11%" class="valorCampoSinTamFijoPeque" valign=top> <font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font> </td> <td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td> <!-- <td width="61%"class="valorCampoSinTamFijoPeque">message text here</td> --> </tr> <tr bgcolor="#FFFFFF"> <td width="9%" class="valorCampoSinTamFijoPeque">2017-08-31T00:00:00</td> <td width="9%" class="valorCampoSinTamFijoPeque">13:21</td> <td width="4%" align=left class="valorcampoSinTamFijoPeque"> <img src="xxx" title=" Out"> </td> <td width="11%" class="valorCampoSinTamFijoPeque" valign=top> <font class="valorcampoSinTamFijoPeque"><a title="clientname" class="valorcampoSinTamFijoPeque">ClientName</a></font> </td> <td width="14%" class="valorCampoSinTamFijoPeque" width="100%">Subject</td> <!-- <td width="61%"class="valorCampoSinTamFijoPeque">Message Text Here</td> --> </tr> </td> </tr> </table> </td> </tr> </table> </body> </html>';
var adiv = document.createElement("div"),
msgs = [],
trs;
adiv.innerHTML = data;
trs = adiv.querySelectorAll('tr[bgcolor="#FFFFFF"]');
trs.forEach(function(tr){
var d = [];
tr.querySelectorAll("td")
.forEach(function(td){
var img = td.querySelector("img"),
src = img && img.attributes.getNamedItem("src").value;
d.push(src || td.textContent);
});
msgs.push(d);
});
console.log(msgs);
Are you looking for this?
var trs = $('tr[bgcolor="#FFFFFF"]');
var output = [];
for(var i=0;i<trs.length;i++){
var currentOutput = {};
currentOutput.cleintDate=trs.eq(i).find("td").eq(0).text();
//other properties like this
currentOutput.cleintExpirydate=trs.eq(i).find("td").eq(1).text();
//add all your required properties
output.push(currentOutput);
}
console.log(output)
Without jquery
var trs = document.querySelectorAll('tr[bgcolor="#FFFFFF"]');
var output = [];
for(var i=0;i<trs.length;i++){
var currentOutput = {};
currentOutput.cleintDate=trs[i].getElementsByTagName('td')[0].innerText;
//other properties like this
currentOutput.cleintExpirydate=trs[i].getElementsByTagName('td')[0].innerText;
//add all your required properties
output.push(currentOutput);
}
console.log(output)

Unable to get HTML table rows values using jQuery

I have some HTML that looks as follows:
<table id="resultsTable" class="table table-bordered table-responsive table-hover table-condensed sortable">
<thead>
<tr>
<th>Company Name</th>
<th>Tours Offered</th>
<th>Average Rating</th>
<th>Total Reviews</th>
</tr>
</thead>
<tbody class="searchable">
#foreach (var item in Model.AccommodationList)
{
<tr>
<td class="accommodationName">
#Html.ActionLink(item.AccommodationName, "ViewHomePage", "AccommodationHomepage", new {accommodationId = item.AccommodationId}, null)
</td>
<td>
#Html.DisplayFor(modelItem => item.FormattedAddress)
</td>
<td>
<Deleted for brevity>
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalReviews)
</td>
<td class="latitudeCell" style="display: none;">
#Html.DisplayFor(modelItem => item.Latitude)
</td>
<td class="longitudeCell" style="display: none;">
#Html.DisplayFor(modelItem => item.Longitude)
</td>
</tr>
}
</tbody>
</table>
I am trying to get the value of the accommodation name, latitude and longitude in each row with the following jQuery:
$('#resultsTable tbody tr').each(function () {
var latitude = $(this).find(".latitudeCell").html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
});
}
However I must be doing something incorrectly because I'm not able to get any values.
Use javascript table.rows function and textContent property to get the inner text of the cell like you can do something like below:
for(var i = 1, row; row = table.rows[i]; i++)
{
var col1 = row.cells[0].textContent;
var col2 = row.cells[1].textContent;
} var col3 = row.cells[2].textContent;
Don't use innerText it is much slower than textContent and also doesn't work in firefox.
I wrote up a fiddle and modified some of your code so I could put text in your cells, I am wondering if this will help you? If not could you write up a small fiddle and I can provide some more assistance.
https://jsfiddle.net/y3llowjack3t/8cL94hgq/
$('#resultsTable tbody tr').each(function () {
var latitude = $(this).find(".latitudeCell").html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
alert(latitude);
});
You are getting the data correctly but, you don't seem to do anything with the values you obtain from the table. And, after .each(), you will not have access to even the values from the last row since you're using local variables. You can create an array that has all the data.
Give this a try:
var locations = $('#resultsTable tbody tr').map(function() {
var location = {};
location.latitude = $(this).find(".latitudeCell").html();
location.longitude = $(this).find(".longitudeCell").html();
location.accommodationName = $(this).find(".accommodationName").html();
return location;
}).get();
console.log( locations );
//OUTPUT: [{"latitude": "<val>","longitude": "<val>", "accommodationName": "<val>"},{.....},....]
Your code works for me:
example
In the code you paste you put a } more, try to check if there's some issues with brakets.
Here is a working example. In your example, I did not see how you were calling your function. I enclosed your function in $().ready() so that it is called when the DOM is ready. You will want to call your function any time the tan;e content changes.
$().ready(function() {
$('div#cellValues').empty();
$('div#cellValues').append('<ul></ul>');
$('#resultsTable tbody tr').each(function(index) {
var latitude = $(this).find('.latitudeCell').html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
$('div#cellValues ul').append('<li>' + accommodationName + ': [' + latitude + ',' + longitude + ']</li>');
});
});
#cellValues {
border: 1px solid red;
}
#cellValues::before {
content: "Cell Values:";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cellValues"></div>
<table id="resultsTable" class="table table-bordered table-responsive table-hover table-condensed sortable">
<thead>
<tr>
<th>Company Name</th>
<th>Tours Offered</th>
<th>Average Rating</th>
<th>Total Reviews</th>
</tr>
</thead>
<tbody class="searchable">
<tr>
<td class="accommodationName">accomidationName1</td>
<td>FormattedAddress1</td>
<td></td>
<td>TotalReviews1</td>
<td class="latitudeCell" style="display: none;">Latitude1</td>
<td class="longitudeCell" style="display: none;">Longitude1</td>
</tr>
<tr>
<td class="accommodationName">accomidationName2</td>
<td>FormattedAddress2</td>
<td></td>
<td>TotalReviews2</td>
<td class="latitudeCell" style="display: none;">Latitude2</td>
<td class="longitudeCell" style="display: none;">Longitude2</td>
</tr>
<tr>
<td class="accommodationName">accomidationName3</td>
<td>FormattedAddress3</td>
<td></td>
<td>TotalReviews3</td>
<td class="latitudeCell" style="display: none;">Latitude3</td>
<td class="longitudeCell" style="display: none;">Longitude3</td>
</tr>
</tbody>
</table>

How to convert an HTML table to plain text and save it into a variable in JavaScript

I was checking the site and found JavaScript: How to strip HTML tags from string? but this doesn't really explains how to take this:
<tr id="element.incident.comments.additional">
<td colspan="2">
<span style="">
<table cellpadding="0" cellspacing="0" style="table-layout:fixed" width="100%">
<tbody>
<tr>
<td colspan="2">
<hr>
</td>
</tr>
<tr style="">
<td class="tdwrap"><strong>2014-01-23 14:45:40 - <a style="color:blue" href="sys_user.do?sysparm_view=itil&sysparm_query=user_name=Superhero#superhero.com">SuperHero</a></strong></td>
<td align="right" nowrap="true"><sup>Additional comments</sup></td></tr>
<tr style="">
<td colspan="2"><span style="word-wrap:break-word;">received from: SDUperhero#superhero.com<br><br>lalalalalala
<br>lotsofwords<br><br><br><br><br><br>
The information transmitted, including any attachments, is intended only for the person or entity to which it is addressed and may contain confidential and/or privileged material</span></td></tr></tbody></table></span></td>
</tr>
and get the text inside:
<tr id="element.incident.comments.additional">
for further parsing.
I tried with
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent||tmp.innerText;
}
var commentsField = document.getElementById("element.incident.comments.additional").innerHTML;
alert(strip(commentsField));
but I'm not sure if this is the right way as I'm not getting anything in the alert.
Any thoughts?
Because you have . in your ids, you will need to escape them in your jQuery selector:
$("#txt").val($("#element\\.incident\\.comments\\.additional").html());
and that should work.
jsFiddle: http://jsfiddle.net/hescano/EQ9b3/

change td properties and keep value from extracted data from site

I have this structure to get data from another webstie
$searchURL = "http://www.anotherwebsite.com";
$html = file_get_contents($searchURL);
$patternform = '/(<tbody.*<\/tbody>)/sm';
preg_match_all($patternform ,$html,$matches);
preg
echo $matches[0][0];
<tr class="even hidden">
<td colspan="3">OB I</td>
<td colspan="5">vízilabda, ffi</td>
</tr>
<tr class="odd">
<td class="opener nowrap"><ins></ins>063</td>
<td class="center nowrap"><ins class="sport jegkorong" title="jégkorong"><span>jégkorong</span></ins>3</td>
<td><strong>Magyarország - Lengyelország</strong></td>
<td class="center">
1.59 </td>
<td class="center">
4.20 </td>
<td class="center">
3.55 </td>
<td class="nowrap">
P 18:15 </td>
<td class="nowrap">
nov. 08 </td>
</tr>
^^
I had this "input"
Question is:
How can I change three td value to javascript onclick event (extra: that I want to store the name of the event and I want to store the selected odds and add to new div or table line by line.)
I think preg_replace need but regexp. not my desk.
Why must javascript be used? Would simply using the HTML onclick work?
<td onclick="SomethingFunky">

incrementing the value of a input field in the cloned row

1)here i'm doing clone of a row...but this code is working only in eclipse [ ie ,cloning is working ] and it is also not working in any browsers.
2)What is the solution to get the values of text boxes in the cloned rows having same name, and insert into the database using jsp and servlet?
how can i get those values with same name
3)i have servlet code to get only single value from jsp
String address_seq_num =request.getParameter("address_seq_num");
how can i get the value of address seq number in the cloned row fromjsp to servlet to insert into the next row of a table in the database.
4)if i mention "DOCUMENT TYPE" to this code ,it will not work in eclipse also.....
please guide me...
JavaScript
function clonetable() {
var x=document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
var row = document.getElementById("table_row_clone"); // find row to copy
var table = document.getElementById("table_body"); // find table to append to
var clone = row.cloneNode(true); // copy children too
var tb1 = clone.document.getElementById("asn");//here i'm incrementing the value
tb1.value=rowCount+1;//of "address seq num " in the cloned row
clone.id = "abc"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function deltable() {
var x = document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
if (rowCount > 1) {
x.deleteRow(rowCount - 1);
} //delete the last row
}
HTML
<table id="main_table" align="center" style="width:75%">
<tbody id="table_body">
<tr id="table_row_clone">
<td>
<table align="center" style="width:100%">
<tr>
<td align="center">
<div style="border:3px solid silver;border-radius:5px;background-color:grey">
<table width="100%">
<tr>
<th align="center">Address Details</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div style="border:3px solid silver;border-radius:5px;background-color:#1E90FF">
<table align="center" style="width:99%">
<tr style="background-color:#1E90FF">
<td style="width:35%">
<table width="100%">
<tr id="slrow">
<td style="width:43%">Address Seq Num</td>
<td>
<input id="asn" style="width:60px" name="address_seq_num" type="text" value="1" readonly>
</td>
</tr>
</table>
</td>
<td width="49%" align="right">
<input style="width:80%" type="text" value="Reg.office/Primary Office">
</td>
<td align="right">
<input style="width:30px" type="button" value="+" onclick="clonetable()">
<input style="width:30px" type="button" value="-" onclick="deltable()">
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
Per your HTML (which is messy, by the way) you can increment that textbox's value with something like:
var tb = document.getElementById("asn");
tb.value = parseInt(tb.value, 10) + 1;
The trick is you have to cast the textbox's value into a number, which is what parseInt is doing in that example.
Note that the above snippet will give you "NaN" in the textbox if the value is not a valid number - it's not doing any data validation at all.

Categories