Quiero escribir un párrafo y luego tener una barra de búsqueda para buscar si hay una palabra determinada en el párrafo. Si escribo "son" en la barra de búsqueda, me debería decir a través de la alerta "La palabra está en el texto". Y si escribo algo que no está en el texto, me debe decir "No, no está".
Podría verse algo como:
<p id="p1"> Hi, how are you?</p> <input type="text" placeholder="Type something..." id="myInput"> <button type="button" onclick="getInputValue();">Search</button> <script> function 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>
He leído tu pregunta con mucha atención y creo que la siguiente es tu respuesta:
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>
El enfoque ya era bastante bueno. Se adjunta su Javascript revisado. Es insensible a mayúsculas y minúsculas.
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>