使用javascript动态添加选择框的选项值 [英] add option value of the select box dynamically using javascript

查看:89
本文介绍了使用javascript动态添加选择框的选项值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在选择的javascript中填充年份。我做了以下代码。

I want to populate the year in a select javascript. I did the following code.

<html>
<head>
    <script type="text/javascript">         
        $(document).ready(function(){   
            var cur_year=new Date().getFullYear();
            var obj=document.getElementById("yr");  
            alert(obj);         
            for (var i = 2000; i <= 2020; i++)     {                
                opt = document.createElement("option");
                opt.appendChild(document.createTextNode(value));
                opt.selected = selected;
                opt.value = i;
                opt.text=i;
                obj.appendChild(opt);
            }
        });
    </script>
</head>
<body>
    <select id="yr">
<option>year</option>
</select>
</body>
</html>

我不知道这有什么问题。我想填充年份,并希望在用户打开浏览器时在选择框中选择当前年份。任何人都可以帮忙吗?拜托!

I don't know what is wrong in this. I want to populate the year and want to select the current year in the select box when the user opens the browser. Any one can help? please!

推荐答案

$(document).ready( function() { 
            var cur_year=new Date().getFullYear();
            var obj=document.getElementById("yr");         
            for (var i = 2000; i <= 2020; i++)     {                
                opt = document.createElement("option");
                opt.value = i;
                opt.text=i;
                obj.appendChild(opt);
            }
            document.getElementById("yr").value = cur_year;
        });




  1. 只需使用 .value 并将 cur_year 分配给它。

  1. Just Use .value and assign cur_year to it.

工作小提琴

这篇关于使用javascript动态添加选择框的选项值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆