Home > Net >  How to get user input to look in string
How to get user input to look in string

Time:10-28

I want to write a paragraph and then have a search bar to look up if there is a given word in the parapragh. If I write "are" in the search bar, it should tell me through alert "The word is in the text." And if I write something that is not in the text, it should tell me "No, it's not there.".

Could look something like:

<p id="p1"> Hi, how are you?</p>
<input type="text" placeholder="Type something..." id="myInput">
  <button type="button" onclick="getInputValue();">Search</button>

<script>
unction getInputValue(){
  let text = document.getElementById("p1");
  let textElement = document.getElementById(myInput).value;

    if (text.indexOf("textElement") >-1){
      return true;
    } else if
      (text.indexOf("textElement") =-1)
      return false;
console.log(myInput);
  }
</script>

CodePudding user response:

I have read your question very carefully and I think following is your answer:

function getInputValue() {
      let text = document.getElementById("p1").textContent;
      let textElement = document.getElementById('myInput').value;

        if (text.toLowerCase().indexOf(textElement.toLowerCase()) !== -1){
            alert("The word is in the text.");
        } else {
            alert("No, it's not there.");  
        }
      }
    <p id="p1"> Hi, how are you?</p>
    <input type="text" placeholder="Type something..." id="myInput">
      <button type="button" onclick="getInputValue();">Search</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The approach was already quite good. Enclosed is your revised Javascript. It is case insensitive.

function getInputValue() {
  
  let text = document.getElementById("p1").innerHTML;
  
  let textElement = document.getElementById('myInput').value;
  
  if (text.toLowerCase().indexOf(textElement.toLowerCase()) !== -1){
    alert("word found.");
  } else if (text.indexOf(textElement.toLowerCase()) === -1) {
    alert("nothing founded");  
  }
  
  console.log(myInput);
}
<p id="p1"> Hi, how are you?</p>
<input type="text" placeholder="Type something..." id="myInput">
<button type="button" onclick="getInputValue()">Search</button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related