Rookie007
Rookie007

Reputation: 1219

How to increment the year in dropdown box using JavaScript

As I am having very less knowledge in JavaScript cant figure out the solution. I am trying to increment the year in drop down list whenever year changes using JavaScript

I have tried this below code.

function increment()
{
    var temp=document.getElementById("reviewYear_ID");
    var d = new Date();
    var len = temp.options.length;
    if(temp[len-1].value!=d.getFullYear())
    {
        var opt = document.createElement("option");
        var year =   d.getFullYear();
        opt.value=year;
        opt.text=year;
        temp.add(opt,len);
    }
}

JSP code :

<s:select list="#{'2012':'2012'}" headerKey="-11" 
    cssStyle="font-style: arial;font-size: 13px;"
    headerValue="--Select the Year--" name="reviewYear" id="reviewYear_ID"
    theme="simple"  >
  </s:select>

whenever year changes its adding the year to the dropdown but its actually replacing the previous year in that drop down list

for example .. in drop down list we have 2012 only assume this year as 2013 according to my code whenever jan 1 of 2013 comes it will add 2013 to the drop down. I have changed year in my local system to 2014 and tried this code its adding 2014 but replacing the previously added 2013 i want to that append to that drop down value.

Upvotes: 0

Views: 1185

Answers (1)

DutGRIFF
DutGRIFF

Reputation: 5223

If I am understanding right you want to add a option for each year from the last year in the select box to the current year. This fiddle does just that. Try this code in place of your current increment function:

function increment(){
  var temp=document.getElementById("reviewYear_ID");
  var d = new Date();
  var len = temp.options.length;
  var start = temp[len-1].value;
  for(var i=parseInt(start); i < d.getFullYear(); i++){
    var opt = document.createElement("option");
    var year = i+1;
    opt.value=year;
    opt.text=year;
    temp.add(opt,len);
  }
}

Here we are adding each year until we get to the current year. Of course it may just be better to fix your JSP code to use something like list="#{'2012':'2014'}". I am not sure how to do that because I don't know what JSP is but that isn't what you are asking anyways.

Upvotes: 2

Related Questions