javascript += operator - javascript

In my JSON javascript live pull I have:
html += "<tr><td width=60 valign=top><a href='"+item.url+"' target='_blank'>"+item.site+"</a></td>";
The += seems to strip out my tr td values
So I tried amending it to = which just seems to fail.. I tried setting td as a var and still no luck
Any ideas of a way round this, my js is basic so even if you think its silly your answer could help me greatly..
EDIT
to confuse things things further the = alone works in Firefox but on IE the items are loading hidden in the background.. I don't get why the browsers would perform so differently over the use of one + sign...

try:
html += "<tr><td width=60 valign=top><a href='"+item.url+"' target='_blank'>"+item.site+"</a></td></tr>";
Your markup generated is invalid (not closing the anchor tag) so it's possible the browser isn't interpreting the html very well.

x += y is just a shorthand for x = x + y. If you change it to html = "...", you'd be overwriting anything that already existed in the html variable.
How are your "tr td values" being stripped?

Related

How to create a list with formatted items using DOM instead on HTML concatenation?

Please forgive me and let me know if my post is not right since I am brand new to this forum.
I have found most of the answer here (Create a <ul> and fill it based on a passed array), but my problem comes with .createTextNode. My users are using multiple editor boxes to build an outline. Within these boxes they can format the text (underline, color, bold, etc.). So the array items that I am passing to .createTextNode actually have HTML tags in them to format the line items. However .createTextNode makes it just plain text which in turn just spits out the tag instead of applying it when displayed via document.getElementById('foo').appendChild...
I know that I should stay away from HTML concatenation but it is looking very tempting.
Is there any way to retain the formatting of the list items when appended and displayed?
Thank you in advance for your assistance.
Try innerHTML, which will try to parse the content string as HTML structure. For example you have a P tag
<p id="asdf"></p>
<script>
document.getElementById('asdf').innerHTML = 'qwerty';
</script>
Will give you a clickable anchor
<p id="asdf">
qwerty
</p>
But be careful!!! (Notice I use three bang sign here) You must be sure there's no harmful code before you insert it. Check this example:
document.getElementById('asdf').innerHTML = '<img src="image.png" onload="alert(1)">'
You will see an alert dialog. This example is simple though, in practice it can be much more dangerous, e.g. dynamically append a cross site script into you page, aka XSS.
EDIT: here is a demo.
var options = ['Option 1','Option 2'];
function makeUL(){
var LIs = '';
for (i = 0; i < options.length; i += 1){
LIs += '<li>' + options[i] + '</li>';
}
return '<ul>' + LIs + '</ul>';
}
document.getElementById('foo').innerHTML = makeUL();
<div id="foo"></div>

How do I get the proper quotations around the return and end of on click statement?

I've been having some troubles with this javascript code and I am looking for a suggestion. I am programtically adding a row to a table with javascript but I need to add an onclick event for each row. Problem is when the row adds to the page the quotations and upper / lower case has been all converted to lower case causing issues on the web page.
here is the current code
var row = $("<tr id=" + id + " onclick=return SelectRow('Racks','" + id + "') >");
if someone could explain how to get it so that the ending result looked like this
<tr id="r1" onclick="return SelectRow('Racks','r1')">
</tr>
I'm guessing it has to do with escape characters and the order they are being placed but I can't seem to figure it out.
Don't try to generate JavaScript inside HTML inside JavaScript. It is a right pain.
Don't write 90s style code. Stop using onclick attributes. Use event handlers bound with JavaScript.
function row_click_handler(event) {
return SelectRow("Racks", this.id);
}
var row = $("<tr />").attr("id", id).on("click", row_click_handler);

prevent execution of innerHTML

I have a Chrome extension in which I'm fetching tab title and url, and putting them into one single line. Same as Chrome History. I want to separate them visually, dark title, lighter url.
and for that I'm using this code
nodeTitle.innerHTML = tabs[j].title + "<span id='url'>" + ' - ' + tabs[j].url + "</span>" ;
CSS for #url is set and everything works fine, unless page title have some actual HTML code/tag in it, and title get messed (ofc. innerHTML works as it supposed to).
example page...look at title
innerText doesn't help in this situation, because I need < span > treated as it is.
Is there any way to cancel HTML execution for that first part (which can be any variable) or I have to separate them into two different elements and style them?
(and I'm really trying to avoid that)
...maybe check for tags and insert space if any exist??!... relized while writing this question, span tag in pointy brackets :)
You can use createTextNode as an easy (though perhaps not very efficient) way to do this:
function textToHtml(str) {
return document.createTextNode(str).innerHTML;
}
nodeTitle.innerHTML = textToHtml(tabs[j].title) + "<span id='url'>" + ' - ' + textToHtml(tabs[j].url) + "</span>" ;

document.getElementById().innerHTML fails with 'Unknown Error' in IE

I'm trying to use document.getElementById().innerHTML in a JavaScript to change information in a webpage. On FireFox this works as described in the W3C documentation, however, the same method returns 'Unknown Error' in IE. The JavaScript looks like this:
function Change_Info (ID, ROW, VALUE)
{
if (document.getElementById)
{
var ntext = "<td width=4\% bgcolor=#FFFFFF> </td><td width=92\% bgcolor=#FFFFFF colspan=2><font face=Arial size=2 color=#5578C4>" + VALUE + "</font></td><td width=4\% bgcolor=#FFFFFF><center>&nbsp</center></td>";
document.getElementById( ID + "-" + ROW).innerHTML = ntext;
return false;
}
}
The script is called by a MouseOver event like this:
onmouseover='Change_Info("thetag","1","Some Info");
The script would combine ID with a - and then ROW, which, in this example would be, thetag-1. The exact tag does exist in the html document. Using getElementById with the hardcoded tag name, reveils the same error, and the variable method is the prefered one in this situation.
To questions regarding why full html table information is in ntext, for whatever reason nested ID's fail on both FireFox and IE, even though the W3C specification states it should work (obviously both browsers have not fully implimented the W3C specs as persceribed). If someone knows of the way to access and change nested ID's, that works in both FireFox and IE, I'd sure like to know it.
Additionally, as yet I'm only getting this 'Unknown Error' in IE when using innerHTML to change the information. Reading works without error.
Can someone point out where my scripting error is so that I can swap text 'messages' on mouseover events.
IE does not let you add.alter table rows that way. You will need to use DOM Methods removeChild, appendChild, and createElement OR insertRow and insertCell
"Additionally, as yet I'm only getting this 'Unknown Error' in IE when using innerHTML to change the information. Reading works without error."
I faced the same problem and used the following:
var newdiv = document.createElement("div");
newdiv.innerHTML = "new content";
var container = document.getElementById("container");
container.removeChild( container.firstChild );
container.appendChild(newdiv);
http://domscripting.com/blog/display/99
as for getting rid with the ntext, you could do something like
document.getElementById(ID+'-'+ROW).getElementsByTagName('font')[0].innerHTML = VALUE;
If it's the getElementById part that's not working, you'll still be out of luck, though. Try:
var test = document.getElementById(ID+'-'+ROW);
alert(test);
To find out if the object is even found, as to figure out whether you're getting an error because you're trying to access innerHTML on a null error, or if it's actually setting innerHTML that doesn't work. The latter seems probable to me, in which case the proposed solution might help.
Please give jQuery a chance. It very nicely abstracts the browser idiosyncrasies. download latest jquery from jQuery Site and following will suffice:
<script type="text/javascript" src="path/to/jquery"></script>
<script type="text/javascript">
function Change_Info (ID, ROW, VALUE)
{
if (document.getElementById)
{
var ntext = "<td width=4\% bgcolor=#FFFFFF> </td><td width=92\%
bgcolor=#FFFFFF colspan=2><font face=Arial size=2 color=#5578C4>"+ VALUE+
"</font></td><td width=4\% bgcolor=#FFFFFF><center>&nbsp</center></td>";
$("#" + ID + "-" + ROW).html(ntext);
return false;
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$("# ID OF YOUR ELEMENT").mouseover(function(){
Change_Info("thetag","1","Some Info");
});
});
</script>

Javascript read HTML tags

I have a problem and I don't know how to fix it after sometime now, I really need help
So I have asp:GridView, in my DB i am saving text (In English column) with HTML tags, on DataBound event I am using Context.Server.HtmlDecode(encoded); so it is displayed perfectly
But problem is, that also on that event, I am creating OnClick event for that cell ... calling javascript function, and sending parameters to it, it looks like this
ChangeTranslationText('English',
'<div style="text-align: center;"><span style="font-style:italic;">Stavi dole
</span><span style="font-weight: bold;">neki text<br><br><br>Hvala na paznji!
<br><br>Mozes Z da stavis<br><br>Ali Z<br><br>Hvala<br></span></div> '
,'56');return false;
Now in function I am trying that my javascript read that HTML and format my text as it looks like in GridView ...
function ChangeTranslationText(Language, Text, Control) {
document.getElementById("MainContent_txtChangeLanguage").value = Language;
var el = $('<div></div>');
el.html(Text);
document.getElementById("MainContent_txtTranslationText").innerHTML = el.text();
document.getElementById("MainContent_hfControl").value = Control;
$('#ModalChangeTranslate_Fade').modal('show');
}
And I can't format it as I don't know how ... this is best I got so far
Can you help me and advice me how can Javascript read that HTML and keep format like it is in GridView cell?
I made a test here and saw two things:
var el = $('<div></div>'); was throwing $ is not defined. You probably have jquery library in your project, but you actually dont need to declare this el variable. You can use it like you did before:
document.getElementById("MainContent_txtTranslationText").innerHTML = Text;
Another thing was your Text parameter. Not sure if the line breaks is only in the question, but, when we have a string in javascript, it must be on the same line. You can't break lines with "enter". You will need to concatenate the strings to do that, like this:
var html = '<div style="text-align: center;"><span style="font-style:italic;">Stavi dole' +
'</span><span style="font-weight: bold;">neki text<br><br><br>Hvala na paznji!' +
'<br><br>Mozes Z da stavis<br><br>Ali Z<br><br>Hvala<br></span></div>';

Categories

Resources