[英]How to validate form input data in Javascript using JSON information
[英]How to filter form input data with json data in plain javascript?
如果我在輸入表單字段中鍵入標題名稱,我對如何獲取特定結果感到困惑。下面是我嘗試過的代碼。 我會很感激的。謝謝
index.html 文件
<form method="POST">
<input type="text" id="searchName" class="form-control" placeholder="Lorem name">
<button onclick="userAction(event)" class="search-icon"><img src="images/icon.png" alt="submit"></button>
</form>
<ul id="list">
</ul>
JavaScript File
const list = document.getElementById('list');
const searchName = document.getElementById('searchName').value;
const userAction = async (event) => {
event.preventDefault();
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(todos => {
todos.forEach((todo) => {
if(todo===searchName){
const li = document.createElement('li');
li.innerHTML = li.innerHTML = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`;
list.appendChild(li);
}
});
})
}
#searchName
在頁面加載時沒有值,並且您沒有更新 function 中的值,因此如果條件失敗。
您應該在 function 中獲取搜索值。
const list = document.getElementById('list'); const userAction = async (event) => { list.innerHTML = ''; //clear the content on each click event.preventDefault(); const searchName = document.getElementById('searchName').value.trim(); fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json()).then(todos => { todos.forEach((todo) => { if(searchName == todo.title){ const li = document.createElement('li'); li.textContent = `${todo.userId} ${todo.id} ${todo.title} ${todo.completed}`; list.appendChild(li); } }); }) }
<form method="POST"> <input type="text" id="searchName" class="form-control" placeholder="Lorem name"> <button onclick="userAction(event)" class="search-icon"><img src="images/icon.png" alt="submit"></button> </form> <ul id="list"> </ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.