Javascript Error: 'missing ) after argument list" - javascript

I am making an image for my webpage through javascript like so:
photoHTMLString = '<li class = "SliderPhoto"><img src = "' + ImageArray[x].src_small + '" size = "thumb" onclick = "ShowImagePopUP(' + ImageArray[x].src_big + ')" class = "FacebookSliderPhoto"/></li>';
Whenever I try and click a photo go into ShowImagePopUP I get this error:
missing ) after argument list
[Break On This Error] ShowImagePopUp(http://a8.sph...389_84095143389_5917147_2636303_n.jpg)
It doesn't look like I am missing any ')'s so I am lost on the error.
Any suggestions?

You need to wrap the contents of ShowImagePopUP in quotes:
"ShowImagePopUp(\'' + ImageArray[x].src_big + '\')"
Which should render as:
ShowImagePopUp('http://a8.sph...389_84095143389_5917147_2636303_n.jpg')
^ note the quote here
Example: http://jsfiddle.net/V23J6/1/

try
photoHTMLString = '<li class = "SliderPhoto"><img src = "'
+ ImageArray[x].src_small
+ '" size = "thumb" onclick = "ShowImagePopUP(\"'
+ ImageArray[x].src_big + '\")" class = "FacebookSliderPhoto"/></li>';
should do the trick and solve your problem leaving intact the uglyness of you code
A function like this one should be a bit readable and ready to use...
function slideElement(image){
var li=document.createElement('li');
var img=document.createElement('img');
li.appendChild(img);
li.setAttribute('class','SliderPhoto');
img.setAttribute('class','FacebookSliderPhoto');
img.setAttribute('size', 'thumb');
img.setAttribute('src', image.src_small);
img.setAttribute('onclick', function(){showImagePopUP(image.src_big);});
return li;
}

The value in ImageArray[x].src_big needs to be quoted.
Try to avoid building HTML by mashing strings together. Using a DOM builder gives code that is much easier to debug.
You'd probably be better off writing this so the function computes the large URI based on the small URI rather than having it hard coded.

Here's some general advice, build up the strings into intermediate variables and then assemble it at the end. You can then use the debugger to find out where you're getting your ' or "s unbalanced. When you have it all built you can coalesce it into a single line if you want or leave it with the intermediate variables.

Related

Passing parameters in a jQuery variable

I've been away from jQuery development and all js in general for about three years. I can not for the life of me remember how this is supposed to work. This has been going on for four days, and I could really use some help.
Can you tell me what I am doing wrong here:
var $imgAll = $(function(f, a) {
'<img src="' + f + ' alt=&quot' + a + '">';
});
var $imgAC = $imgAll('filename1.jpg', 'Some Alt Text');
var $imgBC = $imgAll('filename2.jpg', 'Some Alt Text');
$page.append($imgAC);
I want an output of code for images whose filenames (f) and alt texts (a) are passed using a single function. It looks like Greek at this point because I'm staring at it constantly.
Thanks for any help!
You'll want $imgAll to be a function, not the return value of a call of $. Here is how it could work:
var $imgAll = function(src, alt) {
return $('<img>').attr({src, alt});
}
var $imgAC = $imgAll('https://stackoverflow.design/assets/img/logos/so/logo-stackoverflow.svg', 'Some Alt Text');
$("body").append($imgAC);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note how the call to attr avoids building the attribute strings yourself, and thereby the potential problems with characters that need escaping. Also, by naming the function parameters as the attribute names (src and alt) you can use the short object literal notation. You could even use an arrow function expression:
const $imgAll = (src, alt) => $('<img>').attr({src, alt});

Dynamically setting variables in javascript

Trying to dynamically set variables depending how many vimeo iframes are on my page. Im using the Eval method in my code below:
var numberVimeoFrames = jQuery(".vimeo").length;
for(i=1;i<=numberVimeoFrames;i++){
var refFrame = jQuery('.vimeo:nth-child(' + i + ')');
eval("player" + i + "= new Vimeo.Player(" + refFrame + ")");
}
My eval line is however generating an error message:
Uncaught SyntaxError: Unexpected identifier
To me it looks like ive concatenated correctly so not sure where ive gone wrong?
Even though in this case I do not think it is that bad, the general opinion is to not use eval at all.
Use arrays instead :
var numberVimeoFrames = jQuery(".vimeo").length;
var players = [];
for(i=1;i<=numberVimeoFrames;i++){
var refFrame = jQuery('.vimeo:nth-child(' + i + ')');
players.push(new Vimeo.Player(refFrame));
}
You can now access your players by calling the array (for example players[1] instead of player1 and so on.)

could not able to pass string values to javascript function

When trying to pass String value to the javascript function , Uncaught ReferenceError is thrown on the browser console.
Below is the sample code:
function mySampleTest(myId, comments){
alert("myId " + myId);
alert("comments : " + comments);
}
var myTest = function(value, rowIndex) {
var myId = this.grid.getItem(rowIndex).MY_ID;
var comments = this.grid.getItem(rowIndex).COMMENTS;
return "<img src=<%=request.getContextPath()%>/images/image1.gif width=\"25\" height=\"25\" onClick=\"mySampleTest("+ myId +" , "+comments+")\">";
};
The JavaScript function mySampleTest is being called when the user clicks the image but it throws a JavaScript error when I pass the string comments to mySampleTest function. If I remove the comment parameters and just pass the myId to mySampleTest(..), it works fine.
Please suggest how to pass string values to the JavaScript function.
I tried the below also, but didn't work.
return "<img src=<%=request.getContextPath()%>/images/image1.gif width=\"25\" height=\"25\" onClick=\"mySampleTest("+ myId +" , \'' + comments + '\')\">";
As a professor once told me, much of writing code involves "being the computer".
Consider your function's output for a moment and you should see the issue pretty quickly:
<img src=whatever/your/context/path/is/images/image1.gif
width="25" height="25"
onClick="mySampleTest(12345, this is a comment)">
Your javascript is invalid:
mySampleTest(12345, this is a comment)
It should be:
mySampleTest(12345, 'this is a comment') // <--- notice the quotes
Which would translate all the way back to:
return "<img src=\"<%=request.getContextPath()%>/images/image1.gif\" width=\"25\" height=\"25\" onClick=\"mySampleTest('"+ myId +"' , '"+comments+"')\">";
Not to mention your src attribute really needs quotes.

Unexpected Number error

I have been writing a function to allow users to upload images from their local file system to a website using JavaScript. I have successfully been able to upload images to the browser.
I have also written a function to allow the user to delete these images.
var count = 0;
function getPhoto(){
var file = document.getElementById('ad_photo');
var list = document.getElementById('ad_photo_upload');
var fReader = new FileReader();
var photo_list = [];
var counter;
fReader.readAsDataURL(file.files[0]);
fReader.onloadend = function(event){
counter = count.toString();
list.innerHTML += "<li id = 'pic " + counter + "'><img src='" + event.target.result + "'></img><a class = 'close' onclick = 'rem_pic(pic " + counter + ")'>X</a></li>";
photo_list[count] = event.target.result;
count++;
}
}
function rem_pic(theID){
var element = document.getElementById(theID);
element.outerHTML = "";
delete element;
}
My issue is whenever I call the "rem_pic(theID)" function I get a Chrome Browser error message that says "Uncaught SyntaxError: Unexpected number". Does anyone have any clue to why this might be? And how I could possibly improve the functions I have written so they work correctly?
Thanks
This happens because you pass a number to your function:
'rem_pic(pic " + counter + ")'
will render to
'rem_pic(pic 1)'
^ or any other number according to your counter value
And this is wrong as javascript params can't contain spaces.
So you probably need to pass a string:
rem_pic(\"pic " + counter + "\")
Looking at your code seems like you use it's as HTML id attribute. id attribute can't contain space chars too so your code should be like
rem_pic(\"pic" + counter + "\")
if your id in layout has format id="pic1", id="pic2", etc.

Unable to concanate String+Variable+String in Javascript

I am trying to dynamically have my javascript look for an element ID in the DOM.
I am currently using this
var string = "retail";
document.getElementById('markup_'+string+'_percentage').value=z.toFixed(2)+"%";
Where the variable "string" has a value like "retail"
This I thought would give a concatenated string of "markup_retail_percentage".
However it actually gives this as an error message:
document.getElementById("markup_"+string+"_percentage") is null
I have tried also using the "." and " * " operators.
One of my html elements
<input type="text" id="markup_retail_percentage" size="5" name="markup_retail_percentage" value="" readonly />
SOLUTION!!!!
//using a new variable name to be passed to function
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
I see two^w three^w four possibilities:
string doesn't contain what you think it does
you should have an underscore before percentage.
the specified element really doesn't exist! (thanks #jAndy)
it does, but the DOM isn't ready yet (thanks #Yoshi)
It looks like you are missing an underscore ahead of percentage
document.getElementById('markup_'+ string +'percentage')
I think you want
document.getElementById('markup_'+ string +'_percentage')
If you run this code before the Document has finished loading, your markup will not have been fully parsed and the Element with that id will not be accessible using DOM methods.
Solution:
function percentage(elementid)
{
elementid = "markup_" + elementid;
elementid = elementid + "_percentage";
document.getElementById(elementid).value = "a value";
}
I dont know why its working:
-Could be concatenation problem , not allowed to use multiple " + " operators?
-Change variable name ?
But it is working now, so thanks to all!

Categories