72595

Search text in page (jQuery) - What to do if no match

Question:

I have this great function that works like a charm. The script highlights the words in the content as long as it matches. However, I can seem to find the right code to display an error if no result matches the query.

This is the HTML:

<div id="search"> <input type="text" id="searchtxt" /> <input type="button" value="Find" onClick="replaceText();" id="search-resultButton" /> </div>

Copy goes here

And this is the function:

function replaceText() { $("body").find(".search-result").removeClass("search-result"); var searchword = $("#searchtxt").val(); var filter = new RegExp("\\b"+searchword+"\\b", "ig"); if(searchword!=""){ $("body").each(function( ) { $(this).html($(this).html().replace(filter,"<span class='search-result'>" + searchword + "</span>")) ; }); } }

I guess I'm looking for something like:

if(searchword!=""){ $("body").each(function( ) { $(this).html($(this).html().replace(filter,"<span class='search-result'>" + searchword + "</span>")) ; }); } else { alert(“There is no match”) }

But I can't seem to find the way to write it. Any help would be appreciated.

Thank you!

Answer1:

You have messed up quotes alert(“There is no match”). Chances are you just need to fix it so it uses normal quotes before there is any chance it will work:

alert("There is no match")

"“ <-- see how those look different

Oh, and I'm sure this isn't the best way. but you could check if the replaced contents are equal to the original contents, and if so there is no match.

var replaced = $(this).html().replace(filter,"<span class='search-result'>" + searchword + "</span>"); if ($(this).html() == replaced) { //error } else $(this).html(replaced) ;

Answer2:

Couldn't get RegExp to work so I went with :contains. It works great. I hope this can help someone:

function replaceText() { $("body").find(".search-result").removeClass("search-result"); var searchWord = $("#searchtxt").val(); $("body").each(function( ) { $('.module').removeClass('highlight'); //Remove old search highlights $("h1 .last-name:contains('" + searchWord + "')").addClass("search-result"); if ($(".search-result")[0]){ // Do something } else { // No Match } }); }

To solve the case sensitivity issue, I added:

$.expr[":"].contains = $.expr.createPseudo(function(arg) { return function( elem ) { return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); // jQuery 1.8+

I hope this helps.

Recommend

  • Get context for search string in text in C#
  • Replace first occurrence of text using replaceText(searchPattern, replacement)
  • Google Apps Script---Replace Straight Quotation Marks with Curly Ones
  • How do you replace a match, using regex, only if it is not preceded by a given character?
  • Send data from edittext to listview
  • Jquery Mobile pageLoading() Method how does it work?
  • Simulate click Geckofx vb,net
  • How to Cache Real-time Data?
  • Abort upload large uploads after reading headers
  • JSON response opens as a file, but I can't access it with JavaScript
  • Play WS (2.2.1): post/put large request
  • Set the selected item in dropdownlist in MVC3
  • Android fill_parent issue
  • Python CGI os.system causing malformed header
  • DomPDF {PAGE_NUM} not on first page
  • AES padding and writing the ciphertext to a disk file
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • Why doesn't :active or :focus work on text links in webkit? (safari & chrome)
  • Validaiting emails with Net.Mail MailAddress
  • MySQL WHERE-condition in procedure ignored
  • what is the difference between the asp.net mvc application and asp.net web application
  • jquery mobile loadPage not working
  • Web-crawler for facebook in python
  • Properly structure and highlight a GtkPopoverMenu using PyGObject
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • Matrix multiplication with MKL
  • trying to dynamically update Highchart column chart but series undefined
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • How do I configure my settings file to work with unit tests?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • How can I remove ASP.NET Designer.cs files?
  • python draw pie shapes with colour filled
  • Is there any way to bind data to data.frame by some index?
  • Binding checkboxes to object values in AngularJs
  • How can i traverse a binary tree from right to left in java?
  • How to Embed XSL into XML
  • failed to connect to specific WiFi in android programmatically
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal