简体   繁体   中英

Can't get the value of input element

I'm trying to format the value from an input field but I cant get the value

following is the HTML:

<div class="container">
    <input type="text" id="search" />
    <button id="btn" onclick="search()">Search</button>
</div>

And here is JS code:

var searchValue = document.querySelector('#search').value;

function search() {
    console.log(searchValue);
}

Running that code logs empty value but if I remove the.value from querySelector line and use it as

console.log(searchValue.value) ;

then it works

What is the problem here??

This is normal you set you variable searchValue outside of your function search() called on click.

Set your variable inside your function called on click.

If you get the value at a moment it has no value it is normal you get no value.

So if you get the value outside of your click function you won't have it. You must use.value at the moment you have a value.

 function search() { var searchValue = document.getElementById('search').value; console.log(searchValue); }
 <div class="container"> <input type="text" id="search" /> <button id="btn" onclick="search()">Search</button> </div>

Here as you can see we can read the value, because it has one at the time I am asking for. Above you set the value "in theory" after you clicked.

 var searchValue = document.getElementById('search').value; console.log(searchValue); function search() { console.log(searchValue); }
 <div class="container"> <input type="text" id="search" value="TEST"/> <button id="btn" onclick="search()">Search</button> </div>

You only update searchValue once when the page is loaded. At this time your text field still contains nothing (strictly an empty string) which is loaded into searchValue .

I assume you want to load it each time your button is clicked, so you need to do this inside search as demonstrated in the example.

 function search() { //Load the value from the text field each time we need it let searchValue = document.getElementById("search").value; //Log the value in console console.log(searchValue); }
 <div class="container"> <input type="text" id="search" /> <button id="btn" onclick="search()">Search</button> </div>

That should work:

function find()
{
serchValue = document.getElementById("search").value;
console.log(searchValue);
}

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