简体   繁体   中英

not able to console input field value when try to declare it global variable in js

   <input type="text" id='listInput'>
    <button type='button' onclick="addList()">Add</button>

<script>

let input = document.getElementById('listInput').value;

   function addList(){
        console.log(input);
    }
 
</script>

Here I'm trying to get listInput value and display it on console.

when I declare listInput as global varibale, nothing displays on console but when I declare listInput inside the function and make it local then I get the listInput value.

But I want to declare listInput as global and not local to console listInput value using only javascript.

The problem is that when you assign input, the value of the input is empty. You could just try with assigning to input the element and not its value and access the value later on in the code:

<script>

let input = document.getElementById('listInput');

function addList(){
   console.log(input.value);
}
 
</script>

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