unterminated string literal error when storing dynamic content with javascript - javascript

I imagine this has been asked many times but I am having problems with the above error,
What I am trying to do is have a cortina effect menu whose child divs content will change depending on a variable which is coming from a drop down menu.
So I wrote roughly how the content of the div would look for one option in a bid to test it out and this is what I have:
function popupContent(selectedText)
{
return '<div>Operating System:
<a class="changer">+<\/a><select class="firstSelect">
<option>Windows<\/option>
<option>OSX<\/option>
<option>Linux<\/option>
<\/select>
<\/div>
<div>Releases:<a class="changer">+<\/a><select class="secondSelect"><option>11.0<\/option><option>11.2<\/option>
<option>10.1<\/option>
<\/select>
<\/div>';
}
I set the content of the div using $('#divname').html(popupContent(this.name));
When I try to load the page I get a unterminated string literal error, I have spent some time looking around and most of the questions seem to be when the word script is in it (which I don't have) and escaping / characters which I have tried as you can see.
Can anyone shed some light on this please?

Your string has line breaks in it.
You can do this instead:
return '<div>Operating System:' +
'<a class="changer">+<\/a><select class="firstSelect">' +
'<option>Windows<\/option>' +
etc.

Related

Background-image:URL jumbles the url. when made in JS

In my Js script i tried escaping,setting string to another complete variable and everything i can think of doing.
But cant figure out why the "/ "character in the background-image:url("../") is giving me such a hard time.
Here is a piece of code from my Js script.
let image = "../../" + value.image;
receptenMarkup += '<div class="receptImage" style="background-image:url("../../'+ value.image +'");" alt="test"></div><img src="'+ image + '">';
"../../'+ value.image +'" comes back correctly in the console.log as the path.
Image comes back as the correct path.
Example:
../../images/recepten/thai-chicken.jpg
My console.log of the entire markup also shows a correct path.
<div class="receptImage" style="background-image:url("../../images/recepten/noodle- soup.jpg");" alt="test">
but!! here is the Result in the inspector..
RESULT INSPECTOR:
<div class="receptImage" style="background-image:url(" ..="" images="" recepten="" noodle-soup.jpg");"="" alt="test"></div><img src="../../images/recepten/noodle-soup.jpg">
Notice the image url works great and fine!
The CSS part on the other hand gets all sorts of crazy.
I cant get this to work properly and point the background image to the right path.
I collect a lot of Json data and make cards based on that.
the background image needs to be in a div so i can style it in RWD and not deform like an image tag does.
Somehow i cant get this to work.
Can anyone please give me pointers?
I tried
1: using ../../ to escape ../../ to escape
2: using just "/'value.image'" to go to the root of the website as W3 suggests, no go.
I bee at this for hours now and my deadline is approaching..
Please can anyone explain why the / becomes a space and i get stuff like image=.. in there which i didnt even type that wat.
URL and IMG react differently.
The problem isn't the /, it's the mismatched quote characters delimiting the strings and attribute values.
The simple fix for this is to use a template literal:
receptenMarkup += `<div class="receptImage" style="background-image: url('../../${value.image}');" alt="test"></div><img src="${image}">`;
Side note; I would suggest making all paths relative to the site root, not relative to the current page.

How do I allow <img> and <a> tags for innerHTML, but no others? (Making a forum)

I am currently programming a forum using only javascript (No JQuery please). I am doing very well, however, there is one issue I would love help with.
Currently I am getting the post from a database, assigning it to variable MainPost, and then attaching it to a div via a text node:
var theDiv = document.getElementById("MainBody");
var content = document.createTextNode(MainPost);
theDiv.appendChild(content);
This is working quite well, however, I would LOVE to be able to do this:
document.getElementById("MainBody").innerHTML += MainPost;
But I know this would allow people to use ANY html tag they want, even something like "script" followed by javascript code. This would be bad for business, obviously, but I do like the idea of allowing posters to use the "img" tag as well as the "a href" tags. Is there a way to somehow disable all tags except these two for the innerHTML?
Thank you all so much for any help you can offer.
Ok, the first thought that came to my mind when I read this question was to find a regular expression to exclude a specific string in a word. Simple search gave a lot of results from SO.
Starting point - To remove all the HTML tags from a string (from this answer):
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
To exclude a string you would do something like this (again from all the source mentioned above):
(?!StringToBeExcluded)
Since you want to exlcude the <a href and <img tags. The suitable regex in your case could be:
(<(?![\/]?a)(?![\/]?img)([^>]+)>)
Explanation :
Think of it as three capturing groups in succession:
(?![\/]?a) : Negative Lookahead to assert that it is impossible to match the regex containing the string "a" prefixed by zero or one backslashes (Should take care of the a href tags)
(?![\/]?img) : Same as 1, just here it looks for the string "img". I don't know why I allowed the </img> tag. Yes, <img> doesn't have a closing tag. You could remove the [\/]? bit from it to fix this.
([^>]+) : Makes sure to not match > zero or one times to take care of tags that have opening and closing tags.
Now all these capture groups lie between < and >. You might want to try a regex demo that I've created incorporating these three capture groups to take care of ignoring all HTML elements except the image and link tags.
Sidenote - I haven't thoroughly given this regex a try. Feel free to play around with it and tweak it according to your needs. In any case, I hope this gets you started in the right direction.

Multiple character replacements in JS - how to stop replacements on previous results within the same function

I have a ( probably very unclean) script that I intend to convert letters put into a text field into html image tags with corresponding pathways. I know there are probably easier ways of doing this, PHP for example however I am using it as a bit of an experiment to familiarise myself further with JS/Jquery. I have overcome a few obsticles to get where I am now as most of this is new ground for me.
In some cases the letters will have multiple images associated with them that will be selected at random so there are a couple of lines included which do this. These are fine however, the issue comes with the section of code that replaces the letters from the text field with the text and variables that make up the image tag. Whilst they work fine individually, when I want to convert multiple letters the replace overwrites instances of that letter in the previously generated image tag. Any ideas can I stop this? I've tried shifting the points at which the script occurs around but it seems the whole thing is somewhat fragile and haven't been able to create a workable solution.
Code in question:
// replace all instances within variable to generate thumbs
final_result = result.replace(/a/g, str_start+chosen_folder+"a"+random_variation+str_end)
.replace(/e/g, str_start+chosen_folder+"e"+random_variation+str_end);
JS Fiddle here: http://jsfiddle.net/N77wZ/
Many thanks in advance !
Do only a single replace:
final_result = result.replace(/a|e/g, str_start+chosen_folder+"$&"+random_variation+str_end);

Inserted code producing unexpected result

So eventually I want to have a greasemonkey script but for now I have only been working with firebug to test out my html/javascript.
I have this code to insert one button in the HTML toolbar for blogger.
The button is supposed to replace all the with " " as blogger seems to just randomly add into my blogs posts and can cause the published article to look weird (a bunch of words separated in between with s will not want to break in the middle unlike the same words separated with " ").
document.getElementById("postingHtmlToolbar").firstChild.innerHTML += '<div id="SP" class="goog-inline-block goog-toolbar-button" title="SP" role="button" style="-moz-user-select: none;"><div class="goog-inline-block goog-toolbar-button-outer-box"><div class="goog-inline-block goog-toolbar-button-inner-box"><b>SP</b></div></div></div>';
Which trimming away the formatting just leaves us with.
<b>SP</b>
The funny thing is that that same code (minus the href, javascript: stuff) run from firebug works perfectly.
But when it is inserted like this and run it blanks the entire web page and writes the value of document.getElementById('postingHtmlBox').value.replace(/ /g, ' ') into this black page.
Am I forgetting something stupid? Is this supposed to happen? Do I have some stupid syntax error? What would you suggest as a solution?
Don't put JS code in href. use onclick:
<b>SP</b>
Try adding void(0); to the end of the href.
Basically, the output of the last statement (if any) is replacing the document (i've had the same problem), so making the last statement one with no output will avoid the problem

Expansion of Struts 2 Tags Messes Up Rendering Of Page

Often times, when I use struts 2 tags, the loading of a page will be incomplete apparently because of single quote or double quote characters from the struts 2 tag interfering with such characters from javascript.
One example I am very eager to get working is as follows:
var me = '<s:a href=\'http://www.google.com\'>Google Link</s:a>';
$('#appnSelect').html(me);
So what I am concerned about is when single and double quotes are inside that me string on the right side of line 1. Ultimately, I need to get <s:select> to work, but this problem seems to creep in with a number of tags like the above example. Replace the <s:a> tag with an <a> tag, and voila, it works. However, when the <s:a> tag gets expanded, the page will incompletely load.
Is there an easy solution somewhere I am missing? One thing I did try was with the theme attribute setting theme="simple" because sometimes that helps me when the output gets rendered incorrectly. That did not work in this case.
Generating HTML from tags like that in the middle of a JavaScript string constant is always going to be an ugly business. In addition to quote characters, you're also likely to get newlines. Strictly speaking you don't know what you're going to get, and you can't control it.
One thing that comes to mind is that you could drop the tags into dummy <script> blocks marked as a non-JavaScript type:
<script id='anAnchor' type='text/html'>
<s:a href='http://www.google.com'>Google Link</s:a>
</script>
The browser won't try to execute that. You can then do this in your JavaScript code:
$('#appnSelect').html($('#anAnchor').html());
What should work with very little thinking:
<s:a id="google" style="display: none;" href="www.google.com">Google Link</s:a>
Now just grab the the element using the id in your script. Might be better if you set up a class. There are id, style and class attributes for all struts2 tags.
I believe the issue is with your escaping of the single quotes inside the <s:a> tag. In my experience with using <s:url>, I've done the following:
var url = "<s:url value='/someAction.action' />"
I believe the same syntax should hold true for <s:a>.
Additionally, look in your JSP container's error log, and see if you can find an error relating to that <s:a> tag. That may provide some additional insight to the problem.
This is my answer, which will not be the best answer because Pointy's response pointed me in the correct direction. However, up votes still appreciated :)
First, you need the script blocks which are not rendered. I have 2 because a checkbox will toggle between which one is displayed:
<script type="myType" id="abc">
<s:select name="selectName" list="#list1" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
<script type="myType" id="abc2">
<s:select name="selectName" list="#list2" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
Next, I create a region which is blank in the html code
<div id="innerRegion">
</div>
Then, I need to put something on the screen when the page first comes up, so go with this:
<script type="text/javascript">
$(document).ready(function(){
$('#innerRegion').html( $('#abc').html() )
});
I needed to put this at the end of my document because onLoad was already being used by a parent page. So I am saying abc is the correct default.
Then I need logic to handle what happens when the checkbox is pushed:
var buttonPressed = false;
$(window).load(
function()
{
LocalInit();
});
function LocalInit() {
$('#myForm input[name=buttonValue]').change(
function()
{
buttonPressed = !buttonPressed;
if (buttonPressed == true)
{
$('#innerRegion').html( $('#abc2').html() )
} else
{
$('#innerRegion').html( $('#abc').html() )
}
$('#dataId').href = document.location.href;
}
);
}
I think what was tripping me up ultimately was that I was trying to force the s:select tag through jQuery functions when as you see above it did not turn out to be necessary. I could just write the s:select as normal.

Categories