7

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.

1
  • 2
    Look at the syntax highlighting. checkVal looks like a string, no? Commented Apr 10, 2014 at 21:15

4 Answers 4

13

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).

Sign up to request clarification or add additional context in comments.

Comments

4

It should be:

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

The double quotes need to be inside the single quotes.

1 Comment

@user3463538 If the answer helps you check the answer as accepted.
3
'[value=' "+ checkval +"']' 

should be

'[value="' + checkval + '"]'  

You have the quotations in the wrong place, so the double-quotation mark is not being included in your string.

Comments

2

Make sure to escape the quotations with a backslash (you have to escape this backslash too, because backslashes do have a special meaning inside of strings) -> use \\ in front of the quotations. But notice that quotations aren't required in every case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.