在同一行Javascript中动态添加Dropdown和Text Box

时间:2016-06-06 13:41:49

标签: javascript jquery html5

<div class="row">
    <div class="col-md-3" style="padding-top: 10px">
    <class="tg-83xr"> <select id="year" name="year">

    <script>
        var myDate = new Date();
        var year = myDate.getFullYear();

        for(var i = 1900; i < year+1; i++){
            document.write('<option  value="'+i+'">'+i+'</option>');}
    </script></select>
    </div>

    <div class="col-md-3" style="padding-top: 10px">    
        <input type="text" class="form-control" id="d000" enabled size = "30">      
    </div>

    <div class="col-md-3" style="padding-top: 10px">    
    <input type="text" class="form-control" id="d001" enabled size ="30" >      
    </div>
</div>

<script>
    $(document).ready(function(){
    $("#num").click(function () {
    $('#form').append("<div class='row'><div class='col-md-3' style='padding top: 10px'><select class=tg-83xr id='year' > </select></div><div class='col-md-3' style='padding-top: 10px'>   <input type='text' class='form-control' id='d000'>    </div><div class='col-md-3' style='padding-top: 10px'><input type='text' class='form-control' id='d001'></div></div>")});});
</script>

<div id="form">
</div>

<br>
<button id="num"> ADD </button> To add another click here

在这里,我无法在下拉列表中添加选项,其中包含.append()函数中的年份列表(1900-2016)。

2 个答案:

答案 0 :(得分:1)

最好不要使用document.write。您可以使用append()方法添加要选择的选项。

<select id="year" name="year">
  </select>
<script>
var myDate = new Date();
var year = myDate.getFullYear();

for (var i = 1900; i < year + 1; i++) {
  $("#year").append('<option  value="' + i + '">' + i + '</option>');
}
</script>

答案 1 :(得分:1)

var optionsString = "";

for( var i = 1900; i <= 2016; i++ ) // OR for( var i = 1900; i <= new Date().getFullYear(); i++ )
{
    optionsString += '<option value="'+i+'">'+i+'</option>';
}

 $('#form').append("<div class='row'><div class='col-md-3' style='padding top: 10px'><select class=tg-83xr id='year' >"+optionsString+"</select></div><div class='col-md-3' style='padding-top: 10px'>   <input type='text' class='form-control' id='d000'>    </div><div class='col-md-3' style='padding-top: 10px'><input type='text' class='form-control' id='d001'></div></div>")});});