Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: Unexpected string in my JavaScript

I'm getting the Uncaught SyntaxError: Unexpected string error in my JavaScript and I honestly can't figure out what's wrong with the code. I have looked at the similar questions, but I'm unable to find a solution. The error is coming in the line highlighted with an asterisk below.

$("#items1").change(function () {
    if ($(this).data('options') === undefined) {
        $(this).data('options', $('#items2 option').clone());
    }
    var checkval = $(this).val();
/* this line: */ var options = $(this).data('options').filter('[value='"+ checkval +"']');
    $('#items2').html(options);
});

The code is taken from Use jQuery to change a second select list based on the first select list option

I've added the extra quotes around the checkval to get rid of another error, this might be the problem, but if I change it, the other error returns.

like image 634
Mohd Avatar asked Apr 10 '14 21:04

Mohd


People also ask

What is uncaught SyntaxError in Javascript?

The Javascript SyntaxError occurs when trying to interpret code that is not syntactically valid. It is thrown when the Javascript engine comes across tokens or token order that does not conform to Javascript syntax when parsing code.

What does uncaught SyntaxError mean?

The "Uncaught SyntaxError: Unexpected identifier" error occurs for 2 main reasons: Misspelling a keyword, e.g. Let or Class instead of let and class . Having a typo in your code, e.g. a missing or extra comma, parenthesis, quote or bracket.


2 Answers

The problem is this:

'[value=' "+ checkval +"']'
^       ^ ^            ^^
1       2 3            45

At 1, you're starting a string; at 2, you're ending it. That means when we reach 3, the start of a new string using double quotes, it's an unexpected string.

You probably want:

'[value="' + checkval + '"]'
^       ^^              ^^ ^
1       23              45 6

At 1, we start the string. 2 is just a " within the string, it doesn't end it. 3 ends it, then we append checkval, then we start a new string (4) with a " in it (5) followed by a ] and then the end of the string (6).

like image 170
T.J. Crowder Avatar answered Oct 24 '22 15:10

T.J. Crowder


It should be:

var options = $(this).data('options').filter('[value="' + checkval + '"]');

The double quotes need to be inside the single quotes.

like image 4
Kyle Needham Avatar answered Oct 24 '22 14:10

Kyle Needham