简体   繁体   English

无法获取输入元素的值

[英]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:以下是 HTML:

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

And here is JS code:这是JS代码:

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运行该代码会记录空值,但如果我从 querySelector 行中删除 .value 并将其用作

console.log(searchValue.value) ; 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.这是正常的,您在单击时调用的 function search()之外设置变量searchValue

Set your variable inside your function called on click.在单击时调用的 function 中设置变量。

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.因此,如果您在点击 function 之外获得价值,您将不会拥有它。 You must use.value at the moment you have a value.你必须在你有值的那一刻使用.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.您只在页面加载时更新searchValue一次。 At this time your text field still contains nothing (strictly an empty string) which is loaded into searchValue .此时,您的文本字段仍然不包含任何内容(严格来说是一个空字符串),这些内容已加载到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.我假设您希望在每次单击按钮时加载它,因此您需要在search中执行此操作,如示例中所示。

 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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