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="">
Related
I'm having a checkbox which is generated dinamically. The Checkbox text contains a string with some html code inside of it. The text comes directly from the database and doesn't display it as html, but just as a string. Is it possible to convert the string to html, so it get displayed correctly? The checkbox:
<label for="id_122_gen">"I hereby consent to the processing of my above-mentioned data according
to the <a href="/declarationofconsent.pdf" target="_blank">declaration of consent." </label>
<input type="checkbox" name="confirm" id="id_122_gen" >
I tried to get the containing text with $.text() method, what worked so far.
$mystring = $("#id_122_gen").text();
After that I've tried to use jQuery method $.parseHTML() and save the result again.
$myhtml = $.parseHTML( $mystring );
Apparantly it is saved as an array, because when I try to save the result again with the $.text() method, it displays:
[object Text],/declarationofconsent.pdf,[object Text]
It's just this. No clickable link and the checkbox disappeared aswell. I'm a bit confused now what to do and don't know how I can display the correct content with a clickable link.
The solution depends on how the html of your page is generated. Your label either has has it's inner html escaped or not.
This is important; inspect view may guide you wrong with escaped HTML and show as proper HTML, so make sure to check the page source.
Most likely your data is HTML escaped and that's why you can't see the link on initial render.
If you see < and > inside the label's source it's HTML escaped.
If it's escaped and you just want to convert it to proper HTML and set it to the label, use this:
$("label[for='id_122_gen']").html( $("label[for='id_122_gen']").text() );
Basically this unescapes the label's value. It reads the innerHTML as text and thus changes the escaped characters to real ones, and when you set it back as it's html value and the innerHTML becomes unescaped.
If you just want to get the link, read on.
If the value inside the label is HTML escaped then you'll have to use .text() to read that value. If it contains unescaped HTML then you'll have to use .html().
Afterwards the flow is the same, you parse the html first.
Since there is text and a link, the parsed html will return as an array with multiple elements. If you just want to get the link you have to search in the array.
You can check out the code below.
$mystring = $("label[for='id_122_gen']").text(); //Use .html() for unescaped
$myhtml = $.parseHTML( $mystring );
var mylink = null;
var e;
while (e = $myhtml.pop())
{
if(e.tagName == "A"){
mylink = e;
break;
}
}
console.log(mylink);
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?
Note: I'm not a javascript expert so please be kind. I continue to get a Null value from a variable that I believe is triggered from a DOM event. I have two functions. One looks at form text whether it is present, if not it pulls from another existing variable so it should never be empty/null. However when I try to pull these variable results into another function it returns Null. I'm trying to have a form where the user enters a filename (picture name) and the script inserts the rest of the string around this filename. Allowing the user to not have to enter a full url path and especially not html code. This works if I put the variables in manually as text strings, I'm just not able to get anything other than null from that variable inside this function.
I thought this was due possibly to the DOM event but I tried everything I could find on here with no success. I even tried making the variable global which didn't help. I'm trying to concatenate text before and after this other variable data. If I put these other variables in as string text it works fine, but whenever I try to pull the other variable outside of the function I get Null. I've mascaraed my java at this point. I've been coming back to this the past few days trying different thing with no success. Thank you.
// This checks for radio toggle and writes html(var string) if on
function output_headshot() {
var text1 = "<td border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><br><img src=\"https://url/Headshots/";
var text2 = headshot_path;
var text3 = "\" width=\"154\" height=\"154\"></td>";
var headshot_html = text1 + text2 + text3;
$(".headshot_element").show();
$(".headshot_element").html(headshot_html);
// Monitor logo option to hide/show
$(".input_headshot input[type=radio]").on("change", function(){
if(document.getElementById('headshot_show').checked) {
$(".headshot_element").show();
$(".headshot_element").html(wpe_headshot_html);
} else if(document.getElementById('headshot_hide').checked) {
$(".headshot_element").hide();
$(".headshot_element").html('');
}
updateHtmlSigRaw()
});
}
output_headshot();
// This looks at form contents, if empty pulls from another static variable employee.headshot_location
// This will display the text string on HTML using this: <span class="output_headshot_location"></span>
$(".input_headshot_location input").on("change keyup paste", function(){
var headshot_location = $(this).val();
if(headshot_location) {
$("span.output_headshot_location").html(headshot_location)
} else {
$("span.output_headshot_location").html(employee.headshot_location);
}
updateHtmlSigRaw()
});
EDIT: Added for context
// Place raw HTML of each version into appropriate containers
function updateHtmlSigRaw() {
get_html_signature_full_visual = document.getElementById("signature-full-visual").innerHTML;
get_html_signature_horizontal_visual = document.getElementById("signature-horizontal-visual").innerHTML;
$("#signature-full-html textarea").text(get_html_signature_full_visual);
$("#signature-horizontal-html textarea").text(get_html_signature_horizontal_visual);
}
This is starting normal variables.
// Start Normal variables
var employee = {
headshot_location: "TimC-Rounded-SQ-SM.png"
}
The following is how I'm placing in HTML for the image to toggle off an on.
<td height="237" valign="middle" style="padding:0px 10px 0px 0;">
<div class="headshot_element" onClick="document.location = 'https://url'" border="0" cellpadding="0" cellspacing="0" >
Next is the form for input.
<div class="input_headshot_location form-group">
<label>Headshot Location</label>
<input class="form-control" type="text" name="headshot_location" placeholder="Enter Full Filename">
</div>
Expecting to pull string from variable to add/concatenate to other static string variables to insert html into page using Span class or Div class.
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>
I want to be able to click on a specific element, and have it send a value to a textarea. However, I want it to append to a specific row/line of the textarea.
What I am trying to build is very similar to what happens when you click the notes of the fret board on this site: http://www.guitartabcreator.com/version2/ In fact, i want it almost exactly the same as this.
But right now I am really just trying to see how I can target the specific row, as it seems doable based on this website.
Currently I am using javascript to send a value based on clicking a specific element.
Here is the js:
<script type="text/javascript">
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
}
</script>
This is the HTML that represents the clickable element:
<td> x </td>
This is the textarea:
<textarea rows="6" cols="24" id="tabText" name="text">-
-
-
-
-
-</textarea>
This works fine for sending the value. But it obviously just goes to the next available space. I am a total newb when it comes to javascript, so I am just not sure where to begin with trying to target a specific line.
What I have currently can be viewed here: http://aldentec.com/tab/
Working code:
After some help, here is the final code that made this work:
<script>
function addNote0(text,element_id) {
document.getElementById(element_id).value += text;
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}}
window.onload = function() {
addNote0('', 'tabText');
};
</script>
Tried to solve this only in JS.
What I did here is use an array to model each row of the textfield (note the array length is 6).
Then I used a jQuery selector to trigger any time a <td> element is clicked which calculates the fret and string that was clicked relative to the HTML tree then calls the updateNote function. (If you change the table, the solution will probably break).
In the update note function, I iterate through the tabTextRows array, adding the appropriate note. Finally, I set the value of the <textarea> to the array joined by '\n' (newline char).
Works for me on the site you linked.
This solution is dependant on jQuery however, so make sure that's included.
Also you should consider using a monospaced font so the spacing doesn't get messed up.
var tabTextRows = ['','','','','',''];
$('td').click(function(){
var fret = $(this).index() - 1;
var line = $(this).parent().index() -1;
updateNote(fret, line);
});
function updateNote(fret, line){
var i;
for(i=0;i<tabTextRows.length;i++){
if(i == line) tabTextRows[i]+='-'+fret+'-';
else tabTextRows[i]+='---';
$('#tabText').val(tabTextRows.join('\n'));
}
}
I wrote the guitartabcreator website. Jacob Mattison is correct - I am using the text area for display purposes. Managing the data occurs in the backend. After seeing your site, it looks like you've got the basics of my idea down.