Html 如何在jsp中使用javascript动态创建下拉框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19497434/
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-29 14:39:51  来源:igfitidea点击:

How to create dropdown box dynamically using javascript in jsp?

javascripthtmljsp

提问by user2867157

I am trying to create drop down boxes dynamically, like when I click on add button it has to create new drop down box. And drop down list also contains dynamic values like it needs to take current year and has to show up to plus five years. please suggest me to do this.

我正在尝试动态创建下拉框,比如当我点击添加按钮时,它必须创建新的下拉框。下拉列表还包含动态值,例如它需要采用当前年份并且必须显示最多加上五年。请建议我这样做。

Thank you..

谢谢..

Here is the code that I tried.

这是我尝试过的代码。

javascript code:

javascript代码:

function Add()
{

  var name1 = document.createElement("select");
  name1.setAttribute('id',"year1")
  name1.setAttribute('oncreate',"Date1()");
}

function Date1(){
  d = new Date();
  curr_year = d.getFullYear();
  for(i = 0; i < 5; i++)
  {
    document.getElementById('year1').options[i] = new Option((curr_year-1)-i,(curr_year-1)-i);
  }
}

html code:

html代码:

<input type="button" name="add" value="Add" onclick="Add();">

回答by vigneshmoha

HTML Code

HTML代码

<div id="select-container">
</div>
<button id="add" onclick="addSelect('select-container');">Add Dropdown</button>

Javascript Code

Javascript代码

function dateGenerate() {
   var date = new Date(), dateArray = new Array(), i;
   curYear = date.getFullYear();
    for(i = 0; i<5; i++) {
        dateArray[i] = curYear+i;
    }
    return dateArray;
}

function addSelect(divname) {
   var newDiv=document.createElement('div');
   var html = '<select>', dates = dateGenerate(), i;
   for(i = 0; i < dates.length; i++) {
       html += "<option value='"+dates[i]+"'>"+dates[i]+"</option>";
   }
   html += '</select>';
   newDiv.innerHTML= html;
   document.getElementById(divname).appendChild(newDiv);
}

Please go through the following fiddle. JS Fiddle to insert select element dynamically

请通过以下小提琴。JS Fiddle动态插入选择元素

It 'll create a select element with option of five consecutive years whenever you click the add dropdown button.

每当您单击添加下拉按钮时,它都会创建一个具有连续五年选项的选择元素。

回答by div

 function abc()
{

 var x=document.getElementById('Select1').value;
var newDiv=document.createElement('div');
var html = '<select id="d2">';
 for(i = x; i < 47; i++) {
   html += "<option value='"+i+"'>"+i+"          </option>";
   }
   html += '</select>';
  newDiv.innerHTML= html;
             document.getElementById('drop').appendChild(newDiv);
   }




 Html:

  <select id='Select1' onchange='abc()'>
  <option value='1'>1</option>
....
 ...
  <div id ='drop'></div>