簡體   English   中英

如何在普通 javascript 中使用 json 數據過濾表單輸入數據?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM