How can I preserve select default option


How can I preserve select default option



I have a select html element for years, I want it's default value to be only "年", but my js code is rewriting it. What should I do?


<select id="f_year" name="f_year">
<option disabled selected value>年</option>
</select>


var start = 1900;
var end = new Date().getFullYear();
var options = "";
for(var year = start ; year "+ year + "年" + "";
}
document.getElementById("f_year").innerHTML = options;




2 Answers
2



When you are recreating the Select options. Instead of keepin var options = ""; keep it as var options = "<option disabled selected value>年</option>";


var options = "";


var options = "<option disabled selected value>年</option>";


<select id="f_year" name="f_year">

</select>


var start = 1900;
var end = new Date().getFullYear();
var options = "年";
for(var year = start ; year "+ year + "年" + "";
}
document.getElementById("f_year").innerHTML = options;



It's better to keep HTML in the HTML when possible…
… So, I would just append your options using += instead of =.


options


+=


=



See it in a working snippet:




var start = 1900;
var end = new Date().getFullYear();
var options = "";
for (var year = start; year <= end; year++) {
options += "<option>" + year +  "年" + "</option>";
}
document.getElementById("f_year").innerHTML += options; // TAKIT: Modified only here!


<select id="f_year" name="f_year">
<option disabled selected value>年</option>
</select>



Hope it helps.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Possible Unhandled Promise Rejection (id: 0): ReferenceError: user is not defined ReferenceError: user is not defined

Opening a url is failing in Swift