sandeep.mishra
sandeep.mishra

Reputation: 825

Javascript code is not working in html dropdown option element

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..?

Upvotes: 0

Views: 155

Answers (3)

Mark Walters
Mark Walters

Reputation: 12390

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

Upvotes: 1

Anthony Grist
Anthony Grist

Reputation: 38345

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

Upvotes: 0

Jonathan
Jonathan

Reputation: 1833

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

Upvotes: 1

Related Questions