Uncaught SyntaxError: Unexpected identifier - javascript

hello im am getting JS error :
Uncaught SyntaxError: Unexpected identifier
here
<script type="text/javascript">
var cur_level = 1;
var ids_arr = new Array(<?php echo $max_level?>);
var im_here = new Array(<?php echo $max_level?>);
ids_arr[0] = 1;
im_here[0] = "|";
function displayData(id, level, used, title)
{
if(used){
choice = document.getElementById('divv'+id).innerHTML;
document.getElementById('test_div').innerHTML = choice;
} else {
document.getElementById('test_div').innerHTML = ' No lerning paths to show.';
updateLinksDiv(id, level, title);
}
}
function updateLinksDiv(id, level, title)
{
var links_div_info = document.getElementById('links_parent_'+id);
var tmpHTML = '';
var here = '';
for(i=0;i<level;i++){
here+= '->'+im_here[i];
links_div_info = document.getElementById('links_parent_'+ids_arr[i]);
tmpHTML += '<div id="divl_'+links_div_info.id+'">'+links_div_info.innerHTML+'</div>';
}
links_div_info = document.getElementById('links_parent_'+id);
tmpHTML += '<div id="divl_'+links_div_info.id+'">'+links_div_info.innerHTML+'</div>';
document.getElementById('links').innerHTML = tmpHTML;
ids_arr[i] = id;
im_here[i] = title;
}
</script>
<script type="text/javascript">
window.onload=updateLinksDiv(1 , 0 , "|" ) ;
</script>
the functions are suppose to create an "expanding" that opens up with levels and everything was working fine untill i added the "title" and i started getting the error.
the error points me to the last and i just cant find the error...
i try to call displayData like this
onclick="displayData('.$cat->id.','.$cat->level.',0,'.$cat->title.')"
any suggestions for what i'm not seeing.?
thank you

In your comment you say that displayData(26,1,0,כיתה ג) is generated. This explains the symptoms, as here the last parameter contains a space in addition to Hebrew letters, so the JavaScript intepreter sees it as two identifiers separated by a space, and the identifiers are probably undefined. Google Chrome gives the error message you describe, whereas Firefox and IE say, more enigmatically, “missing ) after argument list.”
Apparently the generated code is supposed to have the last parameter in quotation marks, i.e. 'כיתה ג'. You need to modify the generation to contain them.

Related

Error: unexpected token ';' at the end of a javascript statement

Just a side note before you try to help: I am a complete newbie. Try to keep things simple ;)
I am trying to code a way to store var values between webpages in HTML. So far I have not been very successful. The problem I am having at the moment is the error 'unexpected token, ';'' (when I paste it into the console on 'Ctrl+Shft+J'
var cookieString = document.cookie;
var savedStats = 0;
var stats = 0;
var fsStat = 0;
var psStat = 0;
var testStat = 0;
function getStats() {
function splitCookieString() {
return savedStats = cookieString.split(',');
}
return stats = [savedstats[0], savedStats[savedstats.length - 1];
return fsStat += stats[0];
return psStat += stats[1];
return testStat = 'Hello World!';
}
}
and it points to the end of the line:
return stats = [savedstats[0], savedStats[savedstats.length -1];
Please help me! Also while I'm here, the Function 'getStats()' has a wierd thing going on where it makes me put two '}' to end it.
The code you posted shows some problems around the understanding of:
The return keyword (structured programming)
The assignment operator (=) (imperative programming)
I strongly recommend to develop some understanding of these concepts.

Unable to Get Output From While Loop in Javascript

I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)

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.

variable string appearing as undefined, new string not appearing in array, javascript

I'm attempting to write some code that puts a single string of emails into an array of emails. Splitting the string wherever there's a comma(,). The initial problem i'm having is the string that is being passed as a variable is not being recognized. I'm getting the error message "Cannot read property 'length' of undefined" of the conditional part of the for loop. Odd, as I'm definitely passing a string or trying to ?
When I pass in a string directly to the function parameter(to avoid the above problem for testing the rest of the function) only the first 2 email addresses appear the final email address is lost ?
I'm learning programming and this is an exercise as such I'm trying to avoid using the split() method or regEx. Daft i know.
Any help in overcoming these 2 issues greatly appreciated.
function separateCommaValues(text)
{
var input = [];
var val = '';
for(var i = 0; i < text.length; i++) {
if(text[i] == ',') {
if(val.length == 0){
continue;
}
input.push(val);
val = '';
} else {
val += text[i];
}
}
document.write( input );
}
separateCommaValues(str);
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
var str = "john#google.com, jake#yahoo.com, andrew#hotmail.com";
separateCommaValues(str);
This is the correct order. Your variable can be declared before it is used via hoisting, but you can't define it before it is used (undefined error).
And the last email address isn't pushed into the array because it doesn't have a comma after it. So after the loop, before document.write( input );, add something like this:
if(val.length > 0){
input.push(val);
val = '';
}

Uncaught SyntaxError: Unexpected token if

I create WordPress ShortCode tab and write this code to collect the shortcode
jQuery('body').on('click', '#tapSubmit',function(){
var shortcode = '[tapWrap]';
jQuery('.tapForm').each(function(){
var title = jQuery('.Title').val(),
content = jQuery('.Content').val(),
shortcode += '[tap ';
if(title){shortcode += 'title="'+title+'"';}
shortcode += ']';
if(content){shortcode += ''+content+'';}
shortcode += '[/tap]';
});
shortcode += '[/tapWrap]';
tinyMCE.activeEditor.execCommand('mceInsertContent', false, shortcode);
});
and i get this error
Uncaught SyntaxError: Unexpected token if
and i try the code in http://jsfiddle.net/ and i got this error in the line which have this code
shortcode += '[tap ';
Expected an assignment or function call and instead saw an expression.
how to fix it ?
When you have
var title = jQuery('.Title').val(),
content = jQuery('.Content').val(),
shortcode += '[tap ';
you are defining new variables in that chain but shortcode is already defined, so you are creating a new variable in this scope. Being a new variable you cannot use +=. Anyway I think you just want to use this:
var title = jQuery('.Title').val(),
content = jQuery('.Content').val(); // changed the last comma with semicolon
shortcode += '[tap ';
To read:
About scope
About var
Problem is coming in here
var title = jQuery('.Title').val(),
content = jQuery('.Content').val(),
shortcode += '[tap ';
shortcode is already a var defined above. You can't use += in a var expression
Just change this to
var title = jQuery('.Title').val(),
content = jQuery('.Content').val(); // note the semicolon here
shortcode += '[tap ';
I think you're also going to run into some nesting issue. Instead of calling jQuery('.Content').val() for each iteration of the loop, I think you're looking for something more like $(this).find('.Content').val() or $('.Content', this). This will find the relevant .Content input in the scope of a given .tapForm.
I'm thinking something like this, but it's just an idea
jQuery('body').on('click', '#tapSubmit', function(){
function title(context) {
var value = jQuery(".Title", context).val();
return value ? 'title="' + value + '"' : '';
}
function content(context) {
var value = jQuery(".Content", context).val();
return value || '';
}
var taps = jQuery('.tapForm').map(function(){
return '[tap ' + title(this) + ']' + content(this) + '[/tap]';
}).join();
tinyMCE.activeEditor.execCommand('mceInsertContent', false, '[tapWrap]' + taps + '[/tapWrap]');
});

Categories