How to set the first value that comes in the dropdown list as the default value in php? The first value should be by default selected when i open my page
Asked
Active
Viewed 6,242 times
0
-
2did you use `selected` attribute of html ? – Rakesh Shetty May 19 '14 at 10:06
-
Show your code so that we can solve your question. – shyammakwana.me May 19 '14 at 10:07
2 Answers
1
This can be achievable using selected attribute of selectbox:
<select name="youselectbox">
<option value="1" selected>Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
Edit :
Give your selectbox a id say "selectme"
<select name="youselectbox" id="selectme">
Then on load use this jQuery :
$(document).ready(function()
{
$("#selectme").prop("selectedIndex", 0); // here 0 means select first option
});
For more information SEE and FIDDLE DEMO
Community
- 1
- 1
Rakesh Shetty
- 4,548
- 7
- 40
- 79
-
The values in the dropdowns are dynamic i.e they are coming from the database.I need to set the first value whichever comes in the dropdown as the default selected value.I am not aware of which values will come.They keep on changing. – user3391126 May 19 '14 at 10:20
0
With selected attribute within the option tag, you set the selected default value of your drop-down.
<select>
<option value="volvo" selected>Volvo</option> # default selected option
<option value="saab">Saab</option>
<option value="vw">VW</option>
<option value="audi">Audi</option>
</select>
EDIT :
For Dynamic Drop-down menu: PHP Code as below
$("#target option:first").attr('selected','selected');
When setting attr selected doesn't work if there's already a selected attribute. The code I use now will first unset the selected attribute, then select the first option.
$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');
Gagan Gami
- 10,121
- 1
- 29
- 55
-
The values in the dropdowns are dynamic i.e they are coming from the database.I need to set the first value whichever comes in the dropdown as the default selected value.I am not aware of which values will come.They keep on changing. – user3391126 May 19 '14 at 10:22
-