0

Below javascript to populate years, now need to select year that is posted from frontend.

e.g if year 1903 is sent the option with value 1903 should be selected.

var start = 1900;
var end = new Date().getFullYear();
var options = "";
var yearpost = "<?php echo $year ?>";
for (var year = start; year <= end; year++) {
  options += "<option "
  if (year == yearpost) {
    document.write('selected')
  }
  ">" + year + "</option>";
}
document.getElementById("year").innerHTML = options;
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Possible duplicate of [How do I change an HTML selected option using JavaScript?](https://stackoverflow.com/questions/10911526/how-do-i-change-an-html-selected-option-using-javascript) – Liam Oct 09 '18 at 10:02
  • 2
    Don't use `document.write()`, ever. You'll want `options += "";` A much much better solution though is to simply call `document.getElementById("year").value = yearpost` at the end. –  Oct 09 '18 at 10:04
  • Quick fix: https://jsfiddle.net/khrismuc/en56q83v/ –  Oct 09 '18 at 10:10
  • Thanks @ChrisG for your prompt solution and suggestions – Danish Jamshed Oct 09 '18 at 10:15

2 Answers2

0

You wrongly wote document.write instead of options += inside if block :

var start = 1900;
var end = new Date().getFullYear();
var options = "";
var yearpost = "2011";
for (var year = start; year <= end; year++) {
  options += "<option ";
  if (year == parseInt(yearpost)) {
    options += ('selected')
  }
  options += ">" + year + "</option>";
}
document.getElementById("year").innerHTML = options;
<select id="year"></select>

Or you can simplify the if statement to this:
options += '<option ' + (year == parseInt(yearpost) ? ' selected' : '') + '>' + year + '</option>';

Yashar Aliabbasi
  • 2,663
  • 1
  • 23
  • 35
-1

If I understood correctly you want the option to be selected when it matches the year. The way you're doing it you are writing to the document, instead you should add it to the string you're creating. Inside your if statement try doing this instead : option += "selected"

Ivan
  • 794
  • 2
  • 7
  • 15