[英]Getting the value of a form input
我想知道是否有一種方法可以在不使用事件偵聽器的情況下獲取表單輸入值的值。
這是與此相關的代碼部分:
<form class="searchBar" id="form">
<input type="text" id="search" name="search" placeholder="Search">
<button type="submit" id="submit">
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path fill="#666666" d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z" />
</svg>
</form>
這是我到目前為止嘗試過的:
const form = document.getElementById('form');
const search = document.getElementById('search');
let query;
/*function submitted(event) {
event.preventDefault();
console.log(search.value)
search.value = "";
}
form.addEventListener('submit', submitted);*/
console.log(search.value)
注釋掉的代碼正確顯示了搜索值,但這使用了事件偵聽器。
我想將搜索值分配給query
。 當我注釋掉代碼塊時,在我輸入內容后控制台中沒有顯示任何內容。
想知道如何將search.value
的值分配給query
。
看來您正在嘗試在不提交事件的情況下獲取價值。 如果是,請嘗試這樣做。
const form = document.getElementById('form');
const search = document.getElementById('search');
let query;
search.addEventListener('input', (event) => {
query = event.target.value;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.