OnesQuared OnesQuared - 3 months ago 10
HTML Question

Trying to focus on text inside a html element by user input

I am fairly new to html/javascript and I am trying to get a focus on to a text/word inside of a html element when user inputs values into a text box.

<input type="text" id="search">
<input type="button" id="button" onsubmit="searchKey" value="Find">
<div>
<p>some text here</p>
</div>


so if the user inputs "text" into the input box, it should match the text and focus on to it

Answer

Using jQuery, this jsFiddle is showing a basic highlight on the text that has been found in the paragraphs. I am mentioning basic because it will remove all the html tags inside the paragraph, considering only the raw text from inside.

$('#button').click(function() { // Trigger when button is clicked
  var searchText = $('#search').val(); // Store text of input field
  var foundParagraph = $('p:contains(' + searchText + ')'); // Get the paragraph(s) that contain the search string
  $('p').each(function() {
    $(this).html($(this).text()); // Remove all styling first
  });
  foundParagraph.each(function() {
    $(this).html(($(this).text().replace(searchText, '<span class="matched-text">$&</span>'))); // Highlight with strong text
  })
});
.matched-text {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="search">
<input type="button" id="button" value="Find">
<div>
  <p>some text here</p>
  <p>Lorem ipsum dolor sit amet (text).</p>
</div>

Comments