I have a (simple, I guess) problem with quotes, single quotes, double quotes.
I have a JS that sends data to a php file, which responds sending some data back with json. In the code below, row.Dispon is part of the response (and is working OK). But I want to "echo" row.Element inside getElementById with no success. I've tried "+row.Element+", or "'+row.Element+'". What I'm doing wrong?
if (row.Dispon=="ImageReload") {
var text='Image changed';
document.getElementById(+row.Element+).value="due";
}
Considering your code snippet only, this should do the job for that specific problem:
if (row.Dispon == "ImageReload") {
var text = 'Image changed';
document.getElementById(row.Element).value = "due";
}
You would need quotes (or double quotes) and + operators if you were trying to build a string. See this example:
var id = 42;
document.getElementById('myId' + id).value = 'something';
Assuming that row.Element contains a string already, you can directly pass it to getElementById().
Some advice here:
Read more about functions on MDN
Read more about Document.getElementById on MDN
Consider using Document.querySelector
Related
I have the following javascript code that attempts to insert HTML code dynamically. I have an error the syntax but I do not know how to correct it. Please can someone advise?
loadNextContainer.innerHTML = '<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\''+numDownloadSoFar+'\', \''+maxDownloadLimit+'\', \''+folderName+'\', \''+jsonHashTags+'\', \''+fromDate+'\', \''+toDate+'\', \''+lastScanId+'\')">LoadNext</span>';
ERROR MESSAGE:
Uncaught SyntaxError: Invalid or unexpected token
I believe the error revovles around the function variables. In particular the JSON variable. I cannot change the use of double quotation marks for each element in the JSON. So that has to stay in any solution.
You could try it using backticks like this.
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords('`+numDownloadSoFar+`', '`+maxDownloadLimit+`', '`+folderName+`', '`+jsonHashTags+`', '`+fromDate+`', '`+toDate+`', '`+lastScanId+`')">LoadNext</span>';
Or just escape the double-quotes instead of the single quotes. The way you're doing it, you're unintentionally opening up the string when you try to escape it.
loadNextContainer.innerHTML = "<span class=\"sr_43\" id=\"srloadnext_2\" onclick=\"srt.loadNextMatchRecords('"+numDownloadSoFar+"', '"+maxDownloadLimit+"', '"+folderName+"', '"+jsonHashTags+"', '"+fromDate+"', '"+toDate+"', '"+lastScanId+"')\">LoadNext</span>";
Judging from your image of your variables, none of the template literal solutions are going to help you, because at least one of your parameters is an array.
Yes, it would be possible, with enough effort, to convert that array into a string representation that would work with innerHTML. But it's going to be very difficult. You'd end up needing to use JSON.stringify to get the string version of your array at least.
An easier solution is actually going to be to create the element and then add the onclick operator through pure javascript, like this:
var s = document.createElement('span');
s.className = 'sr_43';
s.id = 'srloadnext_2';
s.innerText = 'LoadNext';
loadNextContainer.appendChild(s);
s.onclick = function(e) {
srt.loadNextMatchRecords(numDownloadSoFar, maxDownloadLimit, folderName, jsonHashTags, fromDate, toDate, lastScanId);
};
Try it with template literals:
loadNextContainer.innerHTML = `<span class="sr_43" id="srloadnext_2" onclick="srt.loadNextMatchRecords(\'${numDownloadSoFar}\', \'${maxDownloadLimit}\', \'${folderName}\', \'${jsonHashTags}\', \'${fromDate}\', \'${toDate}\', \'${lastScanId}\')">LoadNext</span>`;
Edit:
As others already mentioned. Sorry.
This is using Mirth Connect which uses E4x and js.
Basically I have a variable that I want to populate the XML with.
var memberid = "1234";
var fieldsxml = new XML(<fieldvaluelist></fieldvaluelist>);
fieldsxml.field += <fieldvalue templatefieldid="446" value=#memberid/> //memberID
But its giving an error on the 3rd line: (I also tried just memberid without quotes)
DETAILS: TypeError: Open quote is expected for attribute "value"
associated with an element type "fieldvalue".
It works if the third line is this:
fieldsxml.field += <fieldvalue templatefieldid="446" value="memberid"/>
But that just adds the literal string "memberid" . I actually want value="1234" instead.
How can I do this?
Edit: The final XML should look like this.
<fieldvaluelist><fieldvalue templatefieldid="446" value="1234"/></fieldvaluelist>
You're almost there. Instead of using #memberId, use {memberId}:
fieldsxml.field += <fieldvalue templatefieldid="446" value={memberid}/>;
doesn't work:
console.log(obj.html_template); // outputs "myfile.html"
var html = fs.readFileSync(JSON.stringify(obj.html_template)); // file not found.
works:
console.log(obj.html_template); // "myfile.html"
var html = fs.readFileSync("myfile.html"); // Works.
I'm going crazy.
> JSON.stringify('myfile.html')
""myfile.html""
Your code is looking for the file "myfile.html" (note the superfluous quotes) in the filesystem. It doesn't exist.
Just look for it without stringification:
var html = fs.readFileSync(obj.html_template);
When you call JSON.stringify, it will convert all the Strings to the JSON format Strings, with surrounding double quotes. Quoting ECMAScript 5.1 Specification for JSON.stringify,
If Type(value) is String, then return the result of calling the abstract operation Quote with argument value.
And the Quote operation, is defined here, which basically surrounds the string with " and takes care of special characters in the String.
So JSON.stringify converts, a string, for example, abcd.txt to "abcd.txt", like this
console.log(JSON.stringify("abcd.txt"));
// "abcd.txt"
which is not equal to abcd.txt.
console.log(JSON.stringify("abcd.txt") == "abcd.txt");
// false
but equal to "abcd.txt".
console.log(JSON.stringify("abcd.txt") == '"abcd.txt"');
// true
So, your program searches for a file named "abcd.txt" instead of abcd.txt. That is why it is not able to find the file and fails.
To fix this problem, just drop the JSON.stringify and pass the string directly, like this
var html = fs.readFileSync(obj.html_template);
why are you using JSON.stringify in the first place? you should be able to just do
var html = fs.readFileSync(obj.html_template);
I'm inserting content with js, that includes an onclick call to a function. This function passes a parameter which contains a database entry, which could contain a ' .
var action = 'Share';
Trouble is that when name contains a single apostrophe it breaks the function call. I've tried doing a string replace on name to replace ' with ' but this seems to still be converted back to a ' by the browser.
Any idea how I can get around this?
Use escape() or after JavaScript version 1.5. use encodeURI() or encodeURIComponent() instead.
Don't write code by mashing strings together with other code. You've got JavaScript inside HTML inside JavaScript and it is a recipe for headaches.
Use DOM manipulation instead.
var a = document.createElement('a');
a.href = "#"; // You should use a button instead of a link to the top of the page
a.className = "facebook-share";
a.addEventListener('click', function () {
facebookWallPost(name);
});
a.appendChild(
document.createTextNode('Share');
);
I have a JS function which is generated by some PHP, the function call is below:
onClick=openPopup('".$row['imgname']."','".$row['adtitle']."','".$row['adviews']."')
Now this works unless the value of $row['adtitle'] contains a JS keyword. The one that brought the bug in my code to my attention was the word 'THIS'. Would there be a way to escape these values, I can't figure it out as I have already used a lot of encapsulation in this call.
Thanks in advance.
EDIT:
openPopup('efc86f7223790e91f423ef1b73278435.jpg','THIS IS A TEST ADVERT 12345678','2')
This call does not work.
openPopup('eada91a6c1197d2f2320e59f45d8ca6b.jpg','is a test','2')
however this one does work..
only thing I could figure was the THIS as when looking at the source, the text following THIS is highlighed differently.
Edit 2 : Here is my function:
function openPopup(imgname,adtitle,adviews) {
document.getElementById('popup').style.display = 'block';
document.getElementById('delimg').src = 'imgstore/' + imgname;
document.getElementById('delAdTitle').innerHTML = adtitle;
document.getElementById('delAdViews').innerHTML = adviews;
document.getElementById('confirm').onclick = function() {
location.href = '?delete=1&id=' + imgname;
}
}
Maybe it’s just a question of proper formatting:
$onclick = 'openPopup('.json_encode($row['imgname']).','.json_encode($row['adtitle']).','.json_encode($row['adviews']).')';
echo 'onClick="'.htmlspecialchars($onclick).'"';
Note that we’re abusing json_encode here to quote the JavaScript string literals. Although we shouldn’t as strictly speaking JSON strings are not a subset of JavaScript strings.