0

I want to bind previous year in a html dropdown option in a html page.Below is my code

<option value="(new Date()).getFullYear() - 1;">(new Date()).getFullYear() - 1;</option>

Is this possible..?

3 Answers 3

1

I don't think you can bind JavaScript to an element in the way you have described without using a framework such as AngularJs.

To do this with vanilla JavaScript you will need to include the JavaScript on the page to populate the option values, I would include it at the bottom of you page, something like this:

(function () {
    var previousYear = new Date().getFullYear() - 1;
    document.getElementById('yearSelect').options[0].value = previousYear;
    document.getElementById('yearSelect').options[0].text = previousYear;
})();

Assuming your html is

<select id='yearSelect'>
    <option></option>
</select>

JSFiddle

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

Comments

1

What you suggest isn't possible that way. You would have to create that option dynamically with JavaScript.

For a select box like this

<select id="mySelect">
   <option value="">Please Select</option>
</select>

the JavaScript would be

function loadOption() {

   var lastYear = new Date().getFullYear() -1; //Grab the year -1

   var newOpt = document.createElement("option"); //Create a new option element
   newOpt.value = lastYear;                       //Set it's value
   newOpt.innerHTML = lastYear;                   //Set it's text
   document.getElementById("mySelect").appendChild(newOpt); //Apend to your select box
}

//Then you can run loadOption() onload of the document or in a script tag underneath the element itself 

Here is a fiddle

Comments

0

Yes, it's possible. However, you can't just arbitrarily place JavaScript code in the middle of your HTML and expect it to be interpreted as JavaScript. That only applies for special attributes (onclick, for example), otherwise you need to use a <script> tag to indicate that it's JavaScript.

That said, I'd create just the HTML <select> element using the HTML, and then add the <option> element(s) using JavaScript, like so:

<select name="test" id="mySelect"></select>

<script type="text/javascript">
    var select = document.getElementById('mySelect');

    var option = document.createElement('option');
    option.value = (new Date()).getFullYear() - 1;
    option.innerHTML = (new Date()).getFullYear() - 1;

    select.appendChild(option);
</script>

jsFiddle demo

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.