In WEB development, the most basic and most commonly used is the addition, deletion, modification, and query of databases. Modifications are often considered as a small part of changes, therefore, we usually fill in the form with the previous content and then display it to the user for modification.
When filling in the default content, we often use value = "<? Php echo $ value?> "Method, for example:
<input type='text' name='username' value='<?php echo $username?>' />
But it is not that simple for the select tag because it does not have the value attribute. We usually use code similar to the following:
<select name="catelog"> <?php foreach($catelogList as $k=>$v){?> <option value="<?php echo $v['id']?>" <?php if($_GET['id']==$v['id'])echo "selected";?>><?php echo $v['catelogName']?></option> <?php }?></select>
In this way, as long as we make similar output and judgment on each select label, we can meet our requirements, but it is a little complicated and not easy to maintain. Below is a method implemented using Jquery:
First, when the select tag is output, the default value is saved to the custom default (others can also be) attribute:
<select name="mid" default="<?php echo $_GET['id']?>"> <?php foreach($catelogList as $k=>$v){?> <option value="<?php echo $v['id']?>"><?php echo $v['catelogName']?></option> <?php }?></select>
Then, import the jquery library file in the head of the document or before </body>:
<script src="/js/jquery-1.7.2.min.js" type="text/javascript"></script>
Finally, we can use js Code to automatically select the default item for the select Tag:
<Script> $ (document ). ready (function (e) {// adjust the default value of the drop-down list $ ("select "). each (function (index, element) {$ (element ). find ("option [value = '" + $ (this ). attr ('default') + "']"). attr ('selected', 'selected') ;}); </script>
In this way, not only does the Code look concise, but the code versatility is very high. We can put the following js Code in a separate general js file and then reference it!
The method is for reference only. Please contact us!