I was working on an application for a website, and I was wondering if there is a way to automatically set a value in a dropdown list to be selected automatically based on a value from a MySQL database? I’m sure there is, but I can;t decide where to start. For example, if a person has a profile on a website that stores their name, address, etc., and they go to update it, I want the dropdown list to automatically set whatever they had originally stored in the database to be selected automatically.
I was trying this:
<script type="text/javascript">
$("#state option[value='CA']").attr("selected", "selected");
</script>
<select id="state" name="state">
<option value="">Select One</option>
<option value="AK">Alaska</option>
<option value="AL">Alabama</option>
<option value="AR">Arkansas</option>
<option value="AZ">Arizona</option>
<option value="CA">California</option>
Etc….
But I can’t seem to get it to work. Once I do get it working, I would like to change it to:
$("#state option[value='<?=$state?>']").attr("selected", "selected");
Any suggestions? Is jQuery even the right tool to use here, or is there a better alternative?
Thanks!
You have to use the document load event since the select list have not been created when the script is executed:
imho it’s the right tool since it makes the view cleaner compared to a server side
ifstatement for every row.