Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 724
OnesQuared Avatar asked Oct 30 '22 22:10

OnesQuared


1 Answers

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.

Edit: The scripts now retains other tags and stylings, but not completely. When trying to find text that will create a conflict with another tag (e.g. <span class="matched-text">(te<strong>xt)</span>.</strong>) will not work, so this instance is cancelled.

$('#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
  var customStylingClass = '.matched-text';
  $(customStylingClass).each(function() {
    var text = $(this).text(); //get span content
    $(this).replaceWith(text); //replace all span with just content
  });
  foundParagraph.each(function() {
    $(this).html(($(this).html().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 (te<b>xt)</b>.</p>
  <p>Styling will <strong>not</strong> be removed <i>anymore</i></p>
  <p>
    Not any <span class="tag">tag</span> at all.
    If there is a conflict with tag closings, the operation will just cancel for the instance.
  </p>
</div>
like image 137
Siavas Avatar answered Nov 12 '22 18:11

Siavas