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.

Community
  • 1
  • 1
Mohd
  • 313
  • 1
  • 4
  • 16

4 Answers4

12

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

It should be:

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

The double quotes need to be inside the single quotes.

Kyle Needham
  • 3,379
  • 2
  • 24
  • 38
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.

BrettL
  • 144
  • 4
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.

machinateur
  • 502
  • 5
  • 10