简体   繁体   中英

Trying to reassign a global variable within a following function unsuccessfully (javascript)

I'm trying to make a basic weather site and I want the user to be able to input the number of days they want displayed. I created a global variable that would hold the number that that user entered. The user clicks submit and the function is called to reassign that variable to the desired number of days. I've checked using console for the value of this variable within the function in charge of reassigning it and it works but when I check the console just outside the function the variable reverts back to its previous value

 <script> var days var table = "" function checkValue(){ var day = document.getElementById("day").value; if (day == 1){ days = 1; } else if (day == 2){ days = 2; } else if (day == 3){ days = 3; } else if (day == 4){ days = 4; } else if (day == 5){ days = 5; } else{ alert("Please enter a number (1-5)"); } } console.log(days); 

the html

 <div class = "main">Please enter the day of the week for which you would like the forcast the be displayed (1-5)</div> <br> <div class="main"> Enter day here:<br> <input id = "day" type = "text" name = "day" value=""><br> <br> <button id = "submit" name ="button" onClick = "checkValue();" value="submit">Submit</button> </div> 

Try following code if you want to keep max day as 5 you can put max = "5" as I placed min = "0"

 (function() { var day = document.getElementById("day").value; document.getElementById("btn").onclick = function() { myNode() }; // alert(day); function myNode(){ var day = document.getElementById("day").value; console.log(day); if (day == 1){ day == 1; } else if (day == 2){ day == 2; } else if (day == 3){ day == 3; } else if (day == 4){ day == 4; } else if (day == 5){ day == 5; } else{ alert("Please enter a number (1-5)"); } } })(); 
 <input type="number" id="day" min="1"> <button id="btn">Click</button> 

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