Automatically select the correct item in the drop-down list

I was working on a website app, and I was wondering if there is a way to automatically set the value in the drop down list, which will be automatically selected based on the value from the MySQL database? I am sure there are, but I cannot decide where to start. For example, if a person has a profile on a website that stores his name, address, etc., and they go to update him, I want the drop-down list to automatically set everything that they were originally saved in the database data to be selected automatically.

I tried to do 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 make it work. As soon as I get his work, 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!

+4
source share
3 answers

You should use the document load event because the selection list was not created when the script was executed:

 <script type="text/javascript"> $(function() { $("#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> 

Is jQuery even the right tool to use here, or is there a better alternative?

imho is the right tool because it makes browsing cleaner than the if on the server side for each line.

+4
source

wrap this in the document ready and it should work fine

 $(function(){ $("#state option[value='CA']").attr("selected", "selected"); });​ 

here is an example: http://jsfiddle.net/VPqny/1/

+1
source

Using .val() shorter and doing it on the DOM ready should be enough - no need to wait for window.load:

 $(document).ready(function() { $('#state').val('<?=$state?>'); }); 
0
source

Source: https://habr.com/ru/post/1402459/


All Articles