0

Below is my drop down in JSP where in I have to show the year values and these year values are populated when the document is ready, for which I have written JavaScript code.

<table align="center">
    <tr>
        <td>
            <b>Select Year ::</b>
        </td>
        <td>
            <select id='getYear' onchange="yearChanged(this.value);">

            </select>
        </td>
    </tr>
     </table>

and the corresponding javascript code that populates the values in it is as follows

$(document).ready(function() {
    var d = new Date();
    var year = d.getFullYear();

    var select = document.getElementById("getYear");

    for(var i=0 ; i < 8; i++){

        var displayPast10Year = (parseInt(year)) - i;
        var option = document.createElement('option');
        option.text = option.value = displayPast10Year;  
        select.add(option, 0);

     }


    select.valueOf(year);
    $("#getYear").val(year); 
    yearChanged(year);

});

My requirement is that the drop down (i.e select tag) shows the year value as 2016 when the document is ready. How do I do so?

Loic P.
  • 691
  • 6
  • 18
  • Possible duplicate of [How can I set the default value for an HTML – jakeehoffmann Mar 31 '17 at 08:23

1 Answers1

0

You're setting it to 2017 when you do $("#getYear").val(year);. If you want it set to 2016, you can either remove that line and add

if (displayPast10Year === 2016) {
  option.selected = 'selected';
}

in your for loop, or you can simply replace it with $("#getYear").val(2016).

Now if you need it to always be current year - 1, replace 2016 with year - 1 in either one of the above solutions.

Ronan
  • 1,482
  • 11
  • 11
  • No this still displays the last populated value (i.e current year - 2017) –  Mar 31 '17 at 09:03
  • Probably because you change it again later. Check my solution on jsfiddle: https://jsfiddle.net/svoc3q7e/ It works fine. – Ronan Mar 31 '17 at 09:08
  • I tried copying exactly your code but don't know why its still not working. –  Apr 03 '17 at 06:18