Can't change span content inside a td HTML using js/php - javascript

I have a php snippet on Wordpress that contains a loop through my SQL that will create a table for user.
On that PHP code, i have a specific var that needs to get a X value from web, i was using PHP to do all of it, but since it's not async, it causes page load to be 10s~
I tried use jQuery/JS, unfortunately, i couldn't change value inside <td>
$charstatus = "
<script>
$.get('isOnline.php?name=".$jsName."', function(data) {
var element = document.querySelector('".$vps.$slot."')
element.innerHTML = data
});
</script>";
Why won't it work?

Related

How do I get the HTML contained within a td using jQuery?

I have a table cell that contains HTML, e.g.,
<td id="test">something™ is here</td>
I have an input field that I want to use to edit the HTML inside the table cell, e.g.,
<input type="text" id="editor" value="">
I need to get the string something™ is here from the table cell so I can put it into the <input> for editing. I have tried
var txt=$("#test").text();
var htm=$("#test").html();
Both of them are returning "something™ is here" rather than the raw HTML - I have a breakpoint in Firebug immediately after setting the two test values, and that's what I'm seeing.
Reading the jQuery documentation, I really expected the .html() method to return the raw HTML I'm looking for, but that's not what is happening.
I know that Javascript doesn't have an encoder like PHP's htmlspecialchars() function and that I have to work around that, but all four of these operations produce the same results:
var enchtm=$("<div/>").text(htm).html();
var enctxt=$("<div/>").text(txt).html();
var htmenc=$("<div/>").html(htm).text();
var txtenc=$("<div/>").html(txt).text();
Every permutatation puts "something™ is here" in the editfield, not the raw HTML.
How do I get the string something™ is here from the table cell into the <input> so I can edit it?
It doesn't exist. Entities are decoded before the DOM is produced, and .html() (which is really just a wrapper for the innerHTML property) doesn't re-encode it because there's no reason for it to -- something™ is exactly as valid a representation of the HTML as something™ is. There is no "completely raw" (pre-character-decoding) view of the HTML provided by the browser.
Suggestion: provide the initial value as the value attribute of the input, instead of having it as the content of the div, so that the flow of data is always one way and this problem doesn't occur.
As the other answers have indicated, what I was trying to do is literally impossible - the original HTML source code that was used to populate the table cell no longer exists in the browser by the time it gets written to the DOM document.
The way I worked around this was using a title attribute on the table cell, e.g.,
// in the PHP/HTML source document
<?php $text='something™ is here'; // the contents of the table cell ?>
<td id="test" title="<?php echo htmlspecialchars($text) ?>"><?php echo $text ?></td>
Now the Javascript is relatively simple:
$("#editor").val($("#test").attr("title"));
The problem with this is that some of these table cells are supposed to have tooltips - which use the title attribute - and some are not. Fortunately for me, the table cells that may contain HTML that needs to be edited never need to show a tooltip, and the ones that show tooltips have simple text that can be retrieved using the .text() method. I can set a class attribute on the cells that need a tooltip, e.g.,
<td class="tooltipped" title="This is a tooltip">Hover here!</td>
I can then use jQuery's .not() method to suppress the tooltips on the cells were the title is being used for storing encoded HTML:
// suppress browser's default tooltip on td titles
$("td[title]").not(".tooltipped").mouseover(function()
{ var elem=$(this);
elem.data("title",elem.attr("title"));
// Using null here wouldn't work in IE, but empty string does
elem.attr("title","");
}).mouseout(function()
{ var elem=$(this);
elem.attr("title",elem.data("title"));
});
I don't think that you would be able to get the exact value as html parses the document and displays the it on the browser and I don't know of any keyword or library that helps to find the exact contents of the element.
But you would use Ajax in this case and get all the contents of the file in the string format to get the exact value.
var client = new XMLHttpRequest();
client.open('GET', './file.html'); // get the file by location
client.onreadystatechange = function() {
if (client.readyState === 4) {
if (client.status === 200) { // when the file is ready
var file_contents = (client.responseText); // the whole file is stored in the string format in the variable
get_value(file_contents); // function get_value fetches the exact value
}
}
}
client.send();
function(str_file) {
var indextest = str_file.indexOf("test"); // fetches the index of test
var indexclosing = str_file.indexOf("</td>"); // fetches the index of closing td tag
var td_content = "";
var condition = false;
for (var i = indextest; i < indexclosing; i++) {
if (str_file.charAt(i - 1) == ">") {
condition = true; // the condition is true when the previous character is '>'
}
if (condition) { // when the condition is true start storing the value in the td_content element
td_content += str_file.charAt(i);
}
};
console.log(td_content) // display it
};
Javascript has escape function but it won't help you in this case, I just did a trick for you, but stay to get best answer.
var htm = $("#test").html().replace(/™/g, '™');
$('#editor').val(htm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="test">something™ is here</td>
</tr>
</table>
<input type="text" id="editor" value="">

How to get the whole HTML value from Dijit Editor

Hello Experts I need help
I'm using dojo Dijit Editor "rich text editor" field in my widget, on page load I fetch HTML text from database and I set the rich text editor with the HTML normally, Then user can edit the displayed text and on page close I have to set the field in database with the source HTML of the edited text by user
the problem is when I do the following "myDB_txt=myEditor.getValue();" getValue() doesn't return the complete HTML code it removes HTML tag and header tag and body tag which causes me troubles.
Simply use myEditorWidget.get("Value") where myEditorWidget refer to your dijit/Editor indtance
To wrap this result you can define a function that return result wraped by html tags
wrapResult(myEditor.get("value")));
function wrapResult(html) {
return "<html> <head></head> <body>"+html+"</body></html>";
}
Here is a Sample with wraped result Fiddle .
Otherwise If you want to get the whole HTML enclosing the content dijit ,
you will get access to it's Iframe ( that has the id="editor_iframe")
and then get get the html document of this last like bellow (here you should import dojo/query package)
query("#editor_iframe")[0].contentDocument.documentElement.outerHTML
Here is another Fiddle .
You could try the following to retrieve the value from your dijit/Editor instance.
var content = myEditor.attr("value");
var openTags = '<html><head></head><body>';
var closeTags = '</body></html>';
var html = openTags + content + closeTags; // use this
or
var htmlWrapper = function(content){
return '<html><head></head><body>' + content + '</body></html>';
};
var html = htmlWrapper(myEditor.attr("value"));

How do I pull data from a HTML table, specifically <td id="word">, using JavaScript?

I have a table that will be populated with data and I need to be able to pull data from specific cells using the cell ID. I have tried using document.getElementById("idName").value but I have now come to understand that the .value is only used with <input> tags. I need the JavaScript code to get the data from the <td> tag, using the ID, and not by hard coding in the information that is in the table as the information will change in that cell.
EDIT: Here is the JavaScript code
'
var RNNo5a = document.getElementById("RN5.5").innerText;
var RNNo5 = document.getElementById("RbR4.4").innerHTML;
var RNN04a = document.getElementById("RN6.4").innerHTML;
//var test;
//if (RNNo5a == RNNo5) {test = RNN04a;}
alert(RNNo5a);
`
The table is filled out by another JavaScript code... could that be the source of my problem?
Try using getElementsById("IdName").innerHTML
The innerHTML property sets or returns the HTML content (inner HTML) of an element.
You can read more on innerHTML here
EDIT RE OP's comment - It works in the below example.
var x = document.getElementById("test").innerHTML;
alert(x);
<p id="test">Hello, World!</p>

Counting classes on another page and displaying them

To save me a lot of work editing a number in when adding a document to a site I decided to use javascript to count the number of elements with a class doc .
I am two main problems:
There is trouble displaying the variable. I initially thought this was because I hadn't added function, however when I tried adding this the variable was still not displayed.
The elements with the class I want to count are on another page and I have no idea how to link to it. For this I have tried var x = $('URL: /*pageURL*/ .doc').length; which hasn't worked.
Essentially I want the total elements with said class name and this to be displayed in a span element.
Currently I have something similar to what's displayed below:
<script>
var Items = $('.doc').length;
document.getElementById("display").innerHTML=Items;
</script>
<span id="display"></span>
Found an example of something similar here where the total numbers of articles are displayed.
Edit:
#ian
This code will be added to the homepage, domain.net/home.html. I want to link to the page containing this documents, domain.net/documents.html. I've seen this done somewhere before and if I remember correctly they used url:domainname.com/count somewhere in their code. Hope this helps.
Here is a jQuery call to retrieve the url "./" (this page) and parse the resulting data for all elements with class "lsep" "$('.lsep', data)". You should get back a number greater than 5 or so if you run this from within your debug console of your browser.
$.get("./", function(data, textStatus, jqXHR)
{
console.log("Instances of class: " + $('.lsep', data).length)
});
One important thing to remember is that you will run into issues if the URL your are trying to call is not in the same origin.
Here's an updated snippet of code to do what you're describing:
$(document).ready(
function ()
{
//var url = "/document.html" //this is what you'd have for url
//var container = $("#display"); //this is what you'd have for container
//var className = '.data'; //this is what you'd have for className
var url = "./"; //the document you want to parse
var container = $("#question-header"); //the container to update
var className = '.lsep'; //the class to search for
$.get(url, function (data, textStatus, jqXHR) {
$(container).html($(className, data).length);
});
}
);
If you run the above code from your browser's debug console it will replace the question header text of "Counting classes on another page and displaying them" with the count of instances the class name ".lsep" is used.
First, you have to wait until the document is ready before manipulating DOM elements, unless your code is placed after the definition of the elements you manipulate, wich is not the case in your example. You can pass a function to the $ and it will run it only when the document is ready.
$(function () {
//html() allows to set the innerHTML property of an element
$('#display').html($('.doc').length);
});
Now, if your elements belongs to another document, that obviously won't work. However, if you have used window.open to open another window wich holds the document that contains the .doc elements, you could put the above script in that page, and rely on window.opener to reference the span in the parent's window.
$('#display', opener.document.body).html($('.doc').length);
Another alternative would be to use ajax to access the content of the other page. Here, data will contain the HTML of the your_other_page.html document, wich you can then manipulate like a DOM structure using jQuery.
$.get('your_other_page.html', function(data) {
$('#display').html($('.doc', data).length);
});

How do I keep javascript from breaking my table in a for loop?

The problem I'm having is that when I try to create a table via javascript, it is closing the table before I actually give the closing tag.
I'm using this solution to record/read cookies
https://stackoverflow.com/a/1960049
What I needed was to make a wishlist from this "array" of cookies, by looping through them all and putting them into a table. (inside the #catalog div)
function loopArray() {
var cookie = $.cookie("testCookie");
var items = cookie ? cookie.split(/,/) : new Array();
$('#catalog').empty();
$('#catalog').append("<table><tr><th>Part #</th><th>Delete</th></tr>");
for(var i=0;i<items.length;i++){
$('#catalog').append("<tr><td width='150'>"+items[i]+"</td><td><a href='javascript:;' onclick='remNum("+i+")'><img src='searchAssets/img/delete.png' /></a></td></tr>");
}
$('#catalog').append("</table>");
}
Not sure why this won't work. Tried cheating with innerHTML but that gave me problems, and I tried using document.write but when using the remNum function to remove the cookie value and refresh the list it completely wipes my whole page out.
This is what my table ends up looking like when I take out the code
<table><tbody><tr><th>Part #</th><th>Delete</th></tr></tbody></table><tr><td width="150">three</td><td><img src="searchAssets/img/delete.png"></td></tr>
You can't add partial mal-formed pieces of HTML with .append(). You have to add fully formed pieces of HTML. This line line $('#catalog').append("<table><tr><th>Part #</th><th>Delete</th></tr>"); is a real problem as it's only a piece of valid HTML and is invalid by itself.
What you can do is accumulate the string of partial HTML in your loop and just append the finished string once to the DOM at the end.
Or, you can add the fully formed HTML for the table, but with no rows and then insert a complete row at a time in your loop.
What you cannot do is append <table>, then some rows and then append </table> at the end. append creates WHOLE HTML objects so append <table> challenges the browser to make an entire object out of it or reject the whole thing.
For example, you can do it like this:
function loopArray() {
var cookie = $.cookie("testCookie");
var items = cookie ? cookie.split(/,/) : new Array();
var html = "<table><tr><th>Part #</th><th>Delete</th></tr>";
for(var i=0;i<items.length;i++){
html += "<tr><td width='150'>"+items[i]+"</td><td><a href='javascript:;' onclick='remNum("+i+")'><img src='searchAssets/img/delete.png' /></a></td></tr>";
}
html += "</table>";
$('#catalog').html(html);
}
What you are doing is wrong. .append doesn't work that way. You need to have the complete tag inside append, not partial content.
In your case I would suggest you put them as a string and append it at the end. See below,
$('#catalog').empty();
var tableContent = [];
tableContent.push("<table><tr><th>Part #</th><th>Delete</th></tr>");
for(var i=0;i<items.length;i++){
tableContent.push("<tr><td width='150'>"+items[i]+"</td><td><a href='javascript:;' onclick='remNum("+i+")'><img src='searchAssets/img/delete.png' /></a></td></tr>");
}
tableContent.push("</table>");
$('#catalog').html(tableContent.join('')); //using .html as you had it emptied earlier.

Categories

Resources