BraveVN
BraveVN

Reputation: 430

PHP set dropdown list default value

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.

Upvotes: 0

Views: 656

Answers (2)

Ajay Kulkarni
Ajay Kulkarni

Reputation: 3039

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.

Upvotes: 1

Disha V.
Disha V.

Reputation: 1864

For ex. If you want to make selected 2015

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

Upvotes: 1

Related Questions