jQuery, Assign td text to a variable and post it - javascript

I am relatively new to JavaScript and have a problem I hope your can help
What I am trying to do is this
$("tr:not(:first-child)").each(function(){
var sitename = $("this" + "td:nth-child(1)").text();
var type= $("this" + "td:nth-child(2)").text();
var address= $("this" + "td:nth-child(3)").text();
var city= $("this" + "td:nth-child(4)").text();
var lat= $("this" + "td:nth-child(5)").text();
var long= $("this" + "td:nth-child(6)").text();
var ftime= $("this" + "td:nth-child(7)").text();
$.post('./watchdog.php',{ oadata: sitename});
}).end().remove();
I am selecting the "tr" in a a table except the first one which contains "th". Then I am just stripping the td and assigning the text value to variable. In the end I am posting this data to a PHP script that basically inserts this in a MySQL DB. the problem is i keep getting NULL value in the database.
Here is my Table as generated in the HTML
Site Name Type Address City Lat Long Fault Time
ISB056 Spur Opposite Plot No. 435, Sector I-10/4 Islamabad 73.04393 33.64677 12:02 PM
ISB078 Spur SEECS NUST H-12 Islamabad Islamabad 72.990044 33.64246 12:02 PM

This
$("this" + "td:nth-child(1)").text()
generates the selector thistd:nth-child(1) which does not make sense at all. I think you want:
$(this).find("td:nth-child(1)").text()
But easier would be to just take an array with e.g.
var data = $(this).children('td').map(function() {
return $(this).text();
}).get();
and then send the data like
$.post('./watchdog.php',{ sitename: data[0], type: data[1],...});

You musn't use 'this' but this so remove your quotes.
You also should use classes.
<tr class="site">
<td class="sitename">...</td>
...
</tr>
That will make your code easier to read and to debug:
$("tr.site").each(function(){
var sitename = $(".sitename",this)
})

Related

Need help to add javascript array contents to an existing piece of HTML code

My front-end skills are fairly limited. I have a trained language model which generates 'tweets'.
I have this javascript function which currently displays the tweets as a paragraph.
function addResponse(msg) {
document.getElementById("results").textContent = ""
var para = document.createElement("div");
var s = "<div class='center' id='gpt2'> <b> Here what our BOT has to say... </b> </br></br>"
i = 1
for (var key in msg){
var value = msg[key];
console.log(value);
s = s + i + ") " + " <b>" + value + "</b> </br></br>"
i = i + 1
}
para.innerHTML = s + "</div>";
document.getElementById('append').appendChild(para);
}
Instead of displaying in a paragraph, I want to display as a proper tweet.
Here is a tailwind CSS implementation to create the UI of the tweet: https://codepen.io/webcrunchblog/pen/xedQVv
Currently this displays a fixed string "Starhopper". What I want to do is, loop through my array object 'msg' and display all the tweets with the proper UI .
Currently the addResponse() is called as part of ajax callback for successful response. From there how can I include the tailwind CSS code so that I can display every array element in its own tweet UI?
Hope the question is clear.
EDIT: Created this codepen if anyone wants to try it out: https://codepen.io/nikhilno1/pen/RwPBWvb
In the output, there is a tweet and three sentences. I want 3 tweets to be created for each of the sentence.
I've updated a bit of your code here: https://codepen.io/rxna/pen/OJVwMOm
The idea is to:
Clone the tweet element, have added a custom class for that:
var articleNode = document.querySelector(".tweet-body");
var clone = articleNode.cloneNode(true);
Update the text within each element:
var title = clone.querySelector(".tweet-text");
title.innerText = value;
And lastly append within the DOM:
document.getElementById("append").appendChild(clone);
It's not perfect but hopefully you'd get the idea.

Json Individual Links in Table column

I have one page with a json table pulling in information from the json api. This works fine. Now my issue is, On the far right column i'm wanting a link to another page of mine, This link will be a unique link. At the moment, As you can see by the code, i can get it to link to the html page 12345, But all the rows link through to this. Which does not help Ha!
I'm ideally wanting the first button to link to 1.html then second button to link to 2.html and so on and so forth.
Here is the code i have so far.
for(var i =0;i < json.results.collection1.length;i++) {
var title = json.results.collection1[i].Name.text;
var venue = json.results.collection1[i].Venue.text;
var date = json.results.collection2[i].Date;
var button = "<button class='redirect-button' data-url='12345.html'>Link</button>";
$("#apple").append("<tbody><tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr></tbody>");
$("#apple").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
Obviously all help would be greatly appreciated. Thanks Sam
Just to explain the comment above
The link you're creating is a <button> but really it's just a string.
So by concatenating the URL part of the string based on something (like your i index in your loop) you can change it to anything you want.
so for example :
var button = "<button class='redirect-button' data-url='" + i + " .html'>Link</button>";
this gives an element that looks like :
<button class='redirect-button' data-url='0.html'>Link</button>
would give you 0.html, 1.html, etc (change the data-url='" + i + " .html' to data-url='" + (i+1) + " .html' and you get 1.html, 2.html, 3.html...)
or if you can change the API to give you a proper link in the return you can make it a bit more readable with:
var button = "<button class='redirect-button' data-url='" + json.results.collection2[i].LinkUrl + " .html'>Link</button>";
results in :
<button class='redirect-button' data-url='abcd.html'>Link</button>
assuming the return is called LinkURL and it's value is 'abcd'
Finally you append this string to the $("#apple") element and then the click event is added that looks for the data-url value and changes the current browser location to that new value.

detecting multiple html tags with javascript and regex

I am building a chrome extension which would read the current page and detect specific html/xml tags out of it :
For example if my current page contains the following tags or data :
some random text here and there
<investmentAccount acctType="individual" uniqueId="1629529524">
<accountName>state bank of america</accountName>
<accountHolder>rahul raina</accountHolder>
<balance balType="totalBalance">
<curAmt curCode="USD">516545.84</curAmt>
</balance>
<asOf localFormat="MMM dd, yyyy">2013-08-31T00:00:00</asOf>
<holdingList>
<holding holdingType="mutualFund" uniqueId="-2044388005">
<description>Active Global Equities</description>
<value curCode="USD">159436.01</value>
</holding>
<holding holdingType="mutualFund" uniqueId="-556870249">
<description>Passive Non-US Equities</description>
<value curCode="USD">72469.76</value>
</holding>
</holdingList>
<transactionList/>
</investmentAccount>
</site>
some data 123
<site name="McKinsey401k">
<investmentAccount acctType="individual" uniqueId="1629529524">
<accountName>rahuk</accountName>
<accountHolder>rahuk</accountHolder>
<balance balType="totalBalance">
<curAmt curCode="USD">516545.84</curAmt>
</balance>
<asOf localFormat="MMM dd, yyyy">2013-08-31T00:00:00</asOf>
<holdingList>
<holding holdingType="mutualFund" uniqueId="1285447255">
<description>Special Sits. Aggr. Long-Term</description>
<value curCode="USD">101944.69</value>
</holding>
<holding holdingType="mutualFund" uniqueId="1721876694">
<description>Special Situations Moderate $</description>
<value curCode="USD">49444.98</value>
</holding>
</holdingList>
<transactionList/>
</investmentAccount>
</site>
So I need to identify say tag and print the text between the starting and ending tag i.e : "State bank of america" and "rahukk"
So this is what I have done till now:
function countString(document_r,a,b) {
var test = document_r.body;
var text = typeof test.textContent == 'string'? test.textContent : test.innerText;
var testRE = text.match(a+"(.*)"+b);
return testRE[1];
}
chrome.extension.sendMessage({
action: "getSource",
source: "XML DETAILS>>>>>"+"\nAccount name is: " +countString(document,'<accountName>','</accountName>')
});
But this only prints the innertext of only the first tag it encounters in the page i.e "State bank of america".
What if I want to print only "rahukk" which is the innertext of last tag in the page or both.
How do I print the innertext of last tag it encounters in the page or how does it print all the tags ?
Thanks in advance.
EDIT : The document above itself is an HTML page i have just put the contents of the page
UPDATE : So I did some here and there from the suggestions below and the best I could reach by this code :
function countString(document_r) {
var test = document_r.body;
var text = test.innerText;
var tag = "accountName";
var regex = "<" + tag + ">(.*?)<\/" + tag + ">";
var regexg = new RegExp(regex,"g");
var testRE = text.match(regexg);
return testRE;
}
chrome.extension.sendMessage({
action: "getSource",
source: "XML DETAILS>>>>>"+"\nAccount name is: " +countString(document)
});
But this gave me :
XML DETAILS>>>>> Retirement Program (Profit-Sharing
Retirement Plan (PSRP) and Money Purchase Pension Plan
(MPPP)),Retirement Program (Profit-Sharing
Retirement Plan (PSRP) and Money Purchase Pension Plan
(MPPP)),Retirement Program (Profit-Sharing
Retirement Plan (PSRP) and Money Purchase Pension Plan
(MPPP))
This again because the same XML was present in the page 3 times and What I want is that regex to match only from the last XML and I don't want the tag names too.
So my desired output would be:
XML DETAILS>>>>> Retirement Program (Profit-Sharing
Retirement Plan (PSRP) and Money Purchase Pension Plan
(MPPP))
you match method is not global.
var regex = new RegExp(a+"(.*)"+b, "g");
text.match(regex);
If the full XML string is valid, you can parse it into an XML document using the DOMParser.parseFromString method:
var xmlString = '<root>[Valid XML string]</root>';
var parser = new DOMParser();
var doc = parser.parseFromString(xmlString, 'text/xml');
Then you can get a list of tags with a specified name directly:
var found = doc.getElementsByTagName('tagName');
Here's a jsFiddle example using the XML you provided, with two minor tweaks—I had to add a root element and an opening tag for the first site.
Regex pattern like this: <accountName>(.*?)<\/accountName>
var tag = "accountName";
var regex = "<" + tag + ">(.*?)<\/" + tag + ">";
var testRE = text.match(regex);
=> testRE contains all your matches, in case of tag=accountName it contains "state bank of america" and "rahukk"
UPDATE
According to this page to receive all matches, instead of only the first one, you smust add a "g" flag to the match pattern.
"g: The global search flag makes the RegExp search for a pattern
throughout the string, creating an array of all occurrences it can
find matching the given pattern." found here
Hope this helps you!
You don't need regular expressions for your task (besides, read RegEx match open tags except XHTML self-contained tags for why it's not a good idea!). You can do this completely via javascript:
var tag = "section";
var targets = document.getElementsByTagName(tag);
for (var i = targets.length; i > 0; i--) {
console.log(targets[i].innerText);
}

Reading and formatting Access data

I'm using JavaScript and HTA to read data in access database (.mdb) on local but having a small issue. My JavaScript code is like this:
function miseryBusiness() {
var box = document.getElementById("lyrics");
box.innerHTML = "";
var db = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='paramore.mdb'";
var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
adoConn.Open(db);
adoRS.Open("SELECT * from 2007_RIOT WHERE track=4", adoConn, 1, 3);
var lyrics = adoRS.Fields("lyrics").value;
box.innerText = lyrics;
adoRS.Close();
adoConn.Close();
}
I have a div in the page with id="lyrics". Function gets the specified cell's value and change's div's inner text to that value.
What I want to do is use innerHTML instead of innerText. And if I use inner HTML I get the cell's value as a single line. I want to add line breaks to the end of the each line. Also an anchor to the beginning of the text.
If I was getting the text from a .txt file I'd use
while(!lyrics.AtEndOfStream) {
box.innerHTML += '<a id="miseryBusiness">' + lyrics.ReadLine() + '<br/>';
}
but this doesn't work with access database. Or I couldn't get it to work. Any ideas?
The HTA and .mdb file I'm using: link1 link2
If the lyrics are in a Memo field with hard line-breaks then the line terminator is almost certainly <cr><lf>, so try the following:
box.innerHTML = '<a id="miseryBusiness">' + lyrics.replace(/\r\n/g, '<br/>');

Is there a limit of the size of data using replaceWIth in jQuery?

I am using the replaceWith() function in jQuery to update my web page. I receive the data from a C# web service program that extracts data from a database to build my HTML code. It works fine except when I replace large amounts of data. In the example that's not working, I replace code in my web page with 39000 bytes of data. After that, none of my links work when clicking on a span to calls a JavaScript function. Is there a limit on the size of data used in the replaceWith() function? The html code I am replacing looks like this:
<td align=left valign=top>
<div id="showitems" class="showitems" style="display:inline; float:left"></div>
</td>
The javascript code looks like this:
function ShowDinerItems() {
var gps = document.getElementById("selectdiner").value;
var pos = gps.indexOf(";");
var len = gps.length;
var latitude = document.getElementById("Hiddenlat").value;
var longitude = document.getElementById("Hiddenlng").value;
var dinerkey = gps.substring(0, pos);
PageMethods.CallShowDinerItems(dinerkey, latitude,longitude, OnShowDinerComplete, OnShowDinerError, dinerkey);
}
function OnShowDinerComplete(result) {
var htmlcode = result[0];
if (result == 'none') {
document.getElementById("Message").value = "Search returned no items";
}
else {
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
var locations = result[1].split(";");
var lat = locations[0];
var lng = locations[1];
markDiner(lat, lng, "", 'map_canvas');
}
}
The reason I am using jquery to build my webpage is to avoid page reloads. I could easily program the webdata content in my C# program which may be more efficient but page reloads are to be avoided as dictated by the people who own the website. I am will try the recommendations given.
Note: I used the following code to make it work.
$('.showitems').html(result[0]);
Using .text will not work as it displays raw data and not html data. Thanks to those who contributed.
To be honest I think you're going about this the wrong way here.
It seems to me that you're using ReplaceWith to completely overwrite the matched tag when you could just as simply change its properties with jQuery.
For example:
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
Could easily be changed to this:
$('.showitems').css('float','none').text(result[0]);
Just how many showItems are there going to be by the way, and how do you know how it compares to how many results you get back from the C# call ?
Edit 2: Sorry, didn't realise that the CSS display attribute wasn't actually changing.

Categories

Resources