0

I am trying to load some select options by using a few JS functions. I want to have one option selected by default if it is equal to a PHP variable defined before.

I receive an error:

Unexpected token

and I am sure I am doing something wrong with the syntax:

This is a section of my JS functions:

for(var i = 0; i < categories.length; i++){
          select.options[i] = new Option(categories[i].val,categories[i].id);   
          if (select.options[i].text== <?php echo '$categoriesSelect'; ?>)
            {
              select.options[i].selected=true;
            }       
        }

The variable $categoriesSelect is defined before the JS. Thank you!

12
  • 3
    remove the quote marks in: "json_encode($categoriesSelect)" Commented Jun 21, 2016 at 9:19
  • 1
    Is this in a .php file executed by PHP...? Commented Jun 21, 2016 at 9:19
  • @ deceze: yes, it is a .php file Commented Jun 21, 2016 at 9:20
  • 1
    What does the $categoriesSelect variable contain, since you pass it through json_encode() (which will return a json object, and not a single value)? Commented Jun 21, 2016 at 9:21
  • 2
    Is the example code you've posted what is output by the PHP page? Commented Jun 21, 2016 at 9:21

2 Answers 2

8

You need to quote your strings.

Change (from your comment):

if (select.options[i]== <?php echo "json_encode($categoriesSelect)"; ?>)

to:

if (select.options[i].text == "<?php echo $categoriesSelect; ?>")

This will validate against the text for the option. Change .text to .value to validate against value for the option.

...also removed json_encode() since the variable only contains a string.

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

1 Comment

Also select.options[i].text should be instead of just select.options[i]
2

You need to remove quotes around php function:

From

if (select.options[i].text== <?php echo '$categoriesSelect'; ?>)

To

if (select.options[i].text== '<?php echo $categoriesSelect; ?>')

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.