5

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

OnesQuared
  • 79
  • 6
  • What do you mean by focus ? (this term usually reffer to the element "you're about to write in") Scroll to the text position on a long page ? – technico Aug 06 '16 at 19:07
  • onsubmit is an attribute of forms, not of input elements. Also, when using inline event handling, the attribute needs to be executable JavaScript code, not just the function name. You could try a "onclick" attribute instead of the "onsubmit," and inlcude parentheses after the function name to turn the attribute value into executable JS code. – Syntax Junkie Aug 06 '16 at 19:11
  • 1
    @technico the method focus(); is what im looking for which i believe is what you are referring to. On some resources I've looked up it was selecting an area, like when you tab select something in the html page so to speak. – OnesQuared Aug 06 '16 at 19:44

2 Answers2

2

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>
Siavas
  • 4,992
  • 2
  • 23
  • 33
  • This is mostly what I'm looking for, It seems to function in the jsfiddle, but when i attempt to try and replicate it on html file on my system I seem to be running into a problem. I'm not sure why, it was literally a copy and paste. – OnesQuared Aug 06 '16 at 20:28
  • Is there any way to keep the styling while doing this function? – OnesQuared Aug 06 '16 at 21:09
  • @OnesQuared, have you included the jQuery library in your html page? If not, here is the script tag for it: `` – Siavas Aug 07 '16 at 09:37
  • yes, I figured it out, i had it at the head tag and it just loaded before the page loaded so I ended up moving the script after the body – OnesQuared Aug 08 '16 at 03:02
0

It can be achieved with a combination of jQuery and JavaScript.

$(document).ready(function() {
    $('#button').click(function() {
 var item = $('#search').val();
        search(item, 'content');
    })
});

function search(searchItem, elementId) {
    // get text content
    var text = $('#' + elementId).text();
    // construct regex based on input
    var regex = new RegExp(searchItem, 'g');
    // generate updated content with highlights
    var newContent = text.replace(regex, "<span style='background-color: yellow'>" + searchItem + "</span>");
    // insert new content
    $('#content').html(newContent);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search">
<input type="button" id="button" value="Find">

<div id='content'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ac neque nunc. Vestibulum at augue tristique, rutrum leo vitae, eleifend mauris. Suspendisse commodo leo felis, auctor convallis sapien aliquam at. Curabitur quis ultricies metus. Maecenas id eros non turpis vestibulum sodales a sed sem. Aenean a sem sapien. Sed malesuada orci enim. Ut iaculis, risus eu dictum congue, ligula orci lobortis dolor, sit amet accumsan risus diam id ipsum. Nunc eget elit quis massa tempus suscipit vel at nisl. Duis et malesuada purus. Sed eu lobortis felis. Donec pretium at nibh nec fringilla. Morbi in massa metus. Curabitur ac velit a nulla pellentesque efficitur. Nullam et pharetra velit. Aliquam augue justo, dictum ut consectetur eget, ullamcorper nec urna. tom

Duis ligula mauris, ultricies sed justo eget, consectetur vehicula neque. Aenean scelerisque magna nulla. Nulla porttitor maximus nunc, vitae vestibulum lectus varius vitae. Suspendisse auctor nunc mauris, vel maximus urna hendrerit vitae. Praesent justo nisi, tristique porttitor pulvinar consequat, porttitor nec orci. Vivamus sit amet feugiat ligula. Sed massa urna, suscipit non eros eget, dapibus sodales turpis. Mauris quis pulvinar nunc.

In fringilla quam sed ipsum mattis, at imperdiet lorem bibendum. Phasellus magna quam, pulvinar ac pellentesque sed, ullamcorper quis lectus. Nam aliquam arcu in orci rutrum, et ullamcorper nulla consequat. Nam quis luctus augue. Proin in blandit lacus, vel dapibus lorem. Pellentesque sem est, mollis condimentum auctor vel, luctus mattis mauris. Integer elementum velit in dolor tincidunt, non volutpat sem vulputate. Mauris ac lobortis eros. Nulla neque justo, euismod eu justo in, maximus aliquam nibh. In tempus leo vel interdum accumsan. Duis fermentum turpis eget metus faucibus malesuada. Donec in massa molestie, scelerisque urna id, porta orci. Etiam sit amet dui ut ipsum interdum condimentum. Ut tincidunt dapibus libero ac vulputate. tom

Quisque faucibus metus nec tellus vulputate ultricies. Donec mattis libero sed augue commodo vulputate. Suspendisse blandit lectus non odio tempor, ac scelerisque massa venenatis. Nam consequat odio a aliquam cursus. Vestibulum vel efficitur erat. Sed mattis, dolor at congue rhoncus, justo neque ornare diam, sit amet tincidunt nunc quam sit amet lacus. Mauris eu luctus ipsum.

Etiam et ante tellus. Donec eget quam ullamcorper, finibus sem sed, dictum libero. Donec in ex dignissim risus commodo lobortis. Nunc tincidunt tortor vitae eros congue, vitae tempor ligula rutrum. Phasellus malesuada arcu in tristique finibus. Pellentesque malesuada at nibh et facilisis. Suspendisse convallis consectetur justo. Donec est metus, convallis ut turpis in, mattis egestas mauris. Pellentesque dui velit, lobortis vitae posuere non, ullamcorper vel magna. Integer nec ante quis massa lacinia laoreet eu nec augue. Sed congue massa eget ligula cursus bibendum. Ut dictum purus nec velit feugiat, quis aliquam ligula accumsan. Mauris finibus massa orci, nec facilisis nibh eleifend sit amet.
</div>
Robert
  • 10,126
  • 19
  • 78
  • 130