使用值属性为选择(下拉)列表设置默认值

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用值属性为选择(下拉)列表设置默认值相关的知识,希望对你有一定的参考价值。

For some reason setting a default value for select elements does not work. This one line of jquery solves that problem. Assign a value (value="something") to the select tag that is to be the default value. With jquery get all select elements with a (value) attribute set. For some reason I couldnt get the value of (value) with jquery, it would only return the first item in the list and not the value of the attribute(value). Oldschool javascript managed to return it though. The result is that when the document becomes ready jquery finds all select boxes and changes their value to the value stored in the attribute(value) of the select tag. This means that you can set default values for select elements in the same way you set them for other elements - by assigning them a (value) - value="whatever"
  1. $(function(){
  2. $('select[value]').each(function(){
  3. $(this).val(this.getAttribute("value"));
  4. });
  5. });
  6.  
  7. //The Markup Looks Like This
  8. <select name="category" id="category" value="php"> //NOTICE value attribute!!!
  9. <option value="ARTICLE">ARTICLE</option>
  10. <option value="PHP">PHP</option> //THIS IS THE DEFAULT OPTION
  11. <option value="mysql">MYSQL</option>
  12. <option value="jQuery">jQuery</option>
  13. <option value="CSS(3)">CSS(3)</option>
  14. </select>

以上是关于使用值属性为选择(下拉)列表设置默认值的主要内容,如果未能解决你的问题,请参考以下文章

html下拉框怎么设置默认值

html下拉框怎么设置默认值

如何令comboBox不能输入,只能选择

Select2:设置下拉列表的默认值,从 C# 模型中获取的数据以剃刀语法

选择下拉菜单的选项时,“无法设置属性‘值’为空”

分别在javascript和JSP中动态设置下拉列表默认值