Uncaught SyntaxError: Unexpected string in my JavaScript

I get Uncaught SyntaxError: Unexpected string error in my JavaScript, and I honestly can't figure out what is wrong with the code. I looked at similar questions, but I can not find a solution. The error falls into 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 the second picklist based on the first picklist option

I added extra quotes around checkval to get rid of another error, this may be a problem, but if I change it, another error will return.

+6
source share
4 answers

It should be:

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

Double quotes must be inside single quotes.

+2
source

The problem is this:

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

At 1 you start the line; at 2, you finish it. This means that when we reach 3, the start of a new line using double quotes, this is an unexpected line.

You probably want:

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

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

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

it should be

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

You have quotes in the wrong place, so the double quote mark is not included in your string.

+2
source

Make sure you avoid quotes with a backslash (you also need to avoid this backslash, since backslashes have special meaning inside strings) → use \\ before quotes. But note that quotes are not required in each case.

+2
source

All Articles