2

I have some issue with this:

<select name="whatever">
<option value="pizza">pizza</option>
<option value="pasta">pasta</option>
<option value="sandwich">sandwich</option>
<option value="cheese">cheese</option>
</select>

Select control always when i "run" it show me as first in drop-down menu a pizza and that mean a pizza is selected by default. So, how i can change this if i want to post cheese to be a default(current active in drop-down) This down is just a example how i want to work my select, you see down a placeholder=5 , that mean this number control will by default use a 5 and i want to do the similar thing with my select control.

<input type='number' placeholder=5 min=0 max=10 step=1>

Thank you!

1 Answers1

1

You simply just put the attribute of selected on to the option you want as your default.

You can use a JavaScript function to get the value from your table and assign this value as the selected option of the drop-down. The options for a select drop-down are identified by an index starting at 0.

In the demo below, I've used buttons to call the JS function. Click on the button to change the selected option:

var sel = document.getElementsByName("whatever")[0];

function defaultOption(option) {
  sel.options[option].selected = 'selected';
}
<button onClick="defaultOption(0)">pizza</button>
<button onClick="defaultOption(1)">pasta</button>
<button onClick="defaultOption(2)">sandwich</button>
<button onClick="defaultOption(3)">cheese</button>
</br>
</br>
<select name="whatever">
  <option value="pizza">pizza</option>
  <option value="pasta">pasta</option>
  <option value="sandwich">sandwich</option>
  <option value="cheese" selected>cheese</option>
</select>
MichaelvE
  • 2,558
  • 2
  • 9
  • 18
  • Yeah, of course, but what if i don't know in advance what need to be "selected" because i send this info(what need to be selected) from my table( my table had one column with buttons and if i click one button select need to show me as default a pizza, if i choose to click some other button then select need to show me something else .. ? – Милош Вељковић Jan 31 '19 at 01:08
  • You can use a JavaScript function to get the value from your table and assign this value as the selected option of the drop-down. The options for a select drop-down are identified by an index starting at 0. I've modified the snippet to show this. – MichaelvE Jan 31 '19 at 02:48