Javascript 使用javascript动态添加选择框的选项值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14827176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:03:40  来源:igfitidea点击:

add option value of the select box dynamically using javascript

javascript

提问by ijarlax

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

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

<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!

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

回答by Muhammad Talha Akbar

$(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. Just Use .valueand assign cur_yearto it.
  1. 只需使用.value并分配cur_year给它。

Working Fiddle

工作小提琴

回答by muthuraja143

<?php 
$current_year = date('Y');
$end_year = date('Y', strtotime('+10 years'));
?>
<label>Year</label><select name="year">
    <?php
for($i=$current_year; $i<=$end_year; $i++)
{
    ?>
    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
    <?php
}
?>
</select>