3

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();">
1
  • That's not JSP. That's JAVASCRIPT. Commented Oct 21, 2013 at 14:39

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Check this updated fiddle too. JS Fiddle Link
2
 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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.