简体   繁体   English

如何在普通 javascript 中使用 json 数据过滤表单输入数据?

[英]How to filter form input data with json data in plain javascript?

I am stuck in little confusion how to fetch the specific result if I type title name in input formfield.Below is code that I have tried.如果我在输入表单字段中键入标题名称,我对如何获取特定结果感到困惑。下面是我尝试过的代码。 I ll appreciate it.Thanks我会很感激的。谢谢

index.html file 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 has no value on page load and you are not updating the value inside the function, thus if condition fails. #searchName在页面加载时没有值,并且您没有更新 function 中的值,因此如果条件失败。

You should take the search value inside the 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