I'm beginner in JavaScript. I can't print this code in HTML..
I want when user add value in first input and second input makes select box for years..
var firstInput = document.getElementById("firstInput").value, secondInput = document.getElementById("secondInput").value, myDiv = '', myResult = document.getElementById("result"); function theYears() { "use strict"; var years; for (years = firstInput; years <= secondInput; years += 1) { myDiv += '<select><option>' + years + '</option></select>'; } } myResult.innerHTML = myDiv;
<input type="text" id="firstInput"> <input type="text" id="secondInput"> <input type="button" id="excute" value="Enter" onclick="theYears();"> <div id="result"></div>
Several problems:
parseInt()
to convert the values from strings to numbers. Otherwise, years += 1
will perform string concatenation, not addition. innerHTML
in the function. You're doing it when the page is loaded, not when the user clicks the button. <select>
each time through the loop. Create <select>
once before the loop, then add <option>
in the loop. function theYears() { "use strict"; var firstInput = parseInt(document.getElementById("firstInput").value), secondInput = parseInt(secondInput = document.getElementById("secondInput").value), myDiv = '', myResult = document.getElementById("result"); var years; myDiv = "<select>"; for (years = firstInput; years <= secondInput; years += 1) { myDiv += '<option>' + years + '</option>'; } myDiv += "</select>"; myResult.innerHTML = myDiv; }
<input type="text" id="firstInput"> <input type="text" id="secondInput"> <input type="button" id="excute" value="Enter" onclick="theYears();"> <div id="result"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.