0

I have a dropdown list in which options are generated by javascript like that:

<select class="form-control" id="which-year" name="which-year">
    <option value="2015">2015</option>
    <option value="2016">2016</option>
    <option value="2017">2017</option>
    etc...
    <!-- options generated by scripts.js -->
</select>

After page loaded, I will retrieve which-year (an integer number) from database and set it as an option in dropdown list above. Problem is I don't know how to add the selected attribute using PHP to those options because they are totally generated by script.
How can I do that.
Thank you.

2 Answers 2

1

For ex. If you want to make selected 2015

$("#which-year option[value=2015]").attr("selected","selected");

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

1 Comment

@BraveVN If you dont use an array to generate the list then this would be a good approach.
1

Try this:

<option value="2015"<?=$row['year'] == '2015' ? ' selected="selected"' : '';?>>2015</option>  

Better to create an array of values and loop through that to create a dropdown.

6 Comments

I tried to add these php code into the js script, however, when the page loaded, it didn't recognize they are PHP.
Why would you add php script in JS? Use it with HTML. If you still want to use it in js, then use it like this: var htmlcontent = "<option value="2015"<?=$row['year'] == '2015' ? ' selected="selected"' : '';?>>2015</option>"
my page extension is .php, the options are generated by script, after that, I retrieve data from db and compare, if which-year = year_from_db then I set the selected value in the dropdown list with which-year
Looks like I must totally use JS to set the selected option.
|

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.