Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dropdown box dynamically using javascript in jsp?

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:

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:

<input type="button" name="add" value="Add" onclick="Add();">
like image 697
user2867157 Avatar asked Nov 27 '25 02:11

user2867157


1 Answers

HTML Code

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

Javascript Code

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

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

like image 135
vigneshmoha Avatar answered Nov 28 '25 14:11

vigneshmoha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!