How to detect if text value of an HTML input is keyword of something with JavaScript

38 Views Asked by At

Is there any way to get estimated text value in input element within JavaScript? Just like on YouTube, you don't need to write the whole video name, just write keyword of it and it will also search

Unfortunately, I have no idea how to do it. This is my HTML code for the input:

<div id="searchBar">
    <input type="text" placeholder="Search..." title="Search..." id="searchInput" oninput="getText()">
</div>

And that's JavaScript:

function getText() {
let searchInput = document.getElementById("searchInput");
if(searchInput.value == 1*1 || What does 1*1 equal to || one times one || 1 times 1) {
alert("1*1 equals to 1!");
}}

Someone has idea on how to do it?

1

There are 1 best solutions below

0
mplungjan On

Perhaps something like this?

window.addEventListener('DOMContentLoaded', () => { // when page content is available
  const searchInput = document.getElementById('searchInput');
  const result = document.getElementById('result');
  searchInput.addEventListener('input', function() { // so we can use "this"
    let val = this.value.trim();
    val = val.replace(/[^0-9\-\+\/\%\*,e]/,''); // only allow digits and operators
    this.value = val;
    try {
      const res = eval(val);
      result.textContent = (res) ? res : "";
    } catch (e) {
      console.log(e.message)
    }
  });
});
<div id="searchBar">
  <input type="text" placeholder="Search..." title="Search..." id="searchInput" />
  <span id="result"></span>
</div>