简体   繁体   中英

How I can print result in HTML by JavaScript

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:

  1. You need to get the values of the inputs in the function. You're getting the values when the page is first loaded, before the user has filled them in.
  2. You need to call parseInt() to convert the values from strings to numbers. Otherwise, years += 1 will perform string concatenation, not addition.
  3. You need to assign to innerHTML in the function. You're doing it when the page is loaded, not when the user clicks the button.
  4. You shouldn't repeat <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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM