3

I want to search a list or library item in SharePoint 2013. We have a big list. We need to search the item on the home web part page. Its working IE, but doesn't work properly in chrome and also the fields have an issue ? I need help ? Thanks

<input type="text" style="width:350px" id="txtSearch" />
<input type="button" style=" font-size:15px;font-family:'Segoe UI 
Light','Segoe UI','Segoe',Tahoma,Helvetica,Arial,sans-serif; background-
color:#0072C6; color:white" id="btnSearch" value="Search" onclick="return 
search();" />
<style>
.highlight {
background-color: #FFFF88;
}
</style>
    <script type="text/javascript" 
src="https://my.ABC.com/sites/sandbox1/TEST/test/SiteAssets/jqueryy-
3.2.0.min.js"></script>
<script type="text/javascript">

 /*
 *This is jQuery Highlight plugin to highlight the result text

 */

jQuery.extend({
highlight: function (node, re, nodeName, className) {
    if (node.nodeType === 3) {
        var match = node.data.match(re);
        if (match) {
            var highlight = document.createElement(nodeName || 'span');
            highlight.className = className || 'highlight';
            var wordNode = node.splitText(match.index);
            wordNode.splitText(match[0].length);
            var wordClone = wordNode.cloneNode(true);
            highlight.appendChild(wordClone);
            wordNode.parentNode.replaceChild(highlight, wordNode);
            return 1; //skip added node in parent
        }
    } else if ((node.nodeType === 1 && node.childNodes) && // only element 
nodes that have children
            !/(script|style)/i.test(node.tagName) && // ignore script and 
style nodes
            !(node.tagName === nodeName.toUpperCase() && node.className === 
className)) { // skip if already highlighted
        for (var i = 0; i < node.childNodes.length; i++) {
            i += jQuery.highlight(node.childNodes[i], re, nodeName, 
className);
        }
    }
    return 0;
}
});

jQuery.fn.unhighlight = function (options) {
var settings = { className: 'highlight', element: 'span' };
jQuery.extend(settings, options);

return this.find(settings.element + "." + settings.className).each(function 
() {
    var parent = this.parentNode;
    parent.replaceChild(this.firstChild, this);
    parent.normalize();
}).end();
};

jQuery.fn.highlight = function (words, options) {
var settings = { className: 'highlight', element: 'span', caseSensitive: 
false, wordsOnly: false };
jQuery.extend(settings, options);

if (words.constructor === String) {
    words = [words];
}
words = jQuery.grep(words, function(word, i){
  return word != '';
});
words = jQuery.map(words, function(word, i) {
  return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
});
if (words.length == 0) { return this; };

var flag = settings.caseSensitive ? "" : "i";
var pattern = "(" + words.join("|") + ")";
if (settings.wordsOnly) {
    pattern = "\\b" + pattern + "\\b";
}
var re = new RegExp(pattern, flag);

return this.each(function () {
    jQuery.highlight(this, re, settings.element, settings.className);
});
};

</script>


<script type="text/javascript">
        function search()

      {


       $("#tasksUL").empty();
      var qry= document.getElementById("txtSearch").value
  var soapEnv =
        "<soapenv:Envelope 
xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
            <soapenv:Body> \
                 <GetListItems 
xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                    <listName>Test</listName> \
                    <viewFields> \
                        <ViewFields> \
                           <FieldRef Name='Title' /> \
 <FieldRef Name='ID' /> \
                       </ViewFields> \
  </viewFields> \
  <query> \
   <Query> 
<Where> 
<or> 
<Contains> 

"+qry+"

<Contains>  

"+qry+"

<Contains>  

"+qry+"

</Query> \
  </query> \
   </GetListItems> \
            </soapenv:Body> \
        </soapenv:Envelope>";

    $.ajax({
        url: 
"https://my.ABC.com/sites/sandbox1/Training/_vti_bin/lists.asmx",
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processResult,
        contentType: "text/xml; charset=\"utf-8\""
    });

  }


function processResult(xData, status) {
// show searching text and image when search button is clicked
var loadhtml="<div id='loading' class='ms-dlgLoadingTextDiv'><span 
style='padding-top: 6px; padding-right: 10px;'><img width='24' height='24' 
title='This animation indicates the operation is in progress. Click to 
remove this animated image.' src='/_layouts/15/images/gears_anv4.gif?
rev=36'/></span><span class='ms-core-pageTitle ms-accentText'>Searching...
</span></div>";

//var totalRows = $(xData.responseXML).find("rs\\:data").attr("ItemCount");
var totalRows =   getZRows(xData.responseXML);
if(totalRows=="0")
{
 $("#loading").remove();
$("#tasksUL").before("<div  id='loading'  style='color:red;font-
size:15px'>No matching records found. Please refine your search.</div>");
return true;
}
$("#tasksUL").before(loadhtml);
    $(xData.responseXML).find("z\\:row, row").each(function() {

// creating hyperlink for each item to display form of that list item
var lnk="<a 
href='https://my.ABC.com/sites/sandbox1/Training/Lists/Test/DispForm.aspx?
ID=" + $(this).attr('ows_ID') + "'>"+ $(this).attr("ows_Title") +"</a>";

        var liHtml = "<li>"+ lnk+"</li>";

// 2 second delay and show searching text and image also highlight the 
result with the searched keyword
setTimeout(function(){
 $("#loading").remove();
 $("#tasksUL").append(liHtml);
$("#tasksUL > li").highlight(document.getElementById("txtSearch").value);
}, 2000);

    });

}

$(document).ready(function(){
// check if enter button is pressed and then search button clicked event is 
called
$('#txtSearch').keypress(function(e){
  if(e.keyCode==13)
  $('#btnSearch').click();
});
});

</script>
<script type="text/javascript">
function getZRows(rXML) {
 var rows;
 var itemCount = $(rXML).find("rs\\:data").attr("ItemCount");
if (rXML.getElementsByTagName("z:row").length == 0 && itemCount == 
undefined) {
rows = rXML.getElementsByTagNameNS("*", "row");
} else {
rows = rXML.getElementsByTagName("z:row");
}
return rows.length;
 }
</script>

<div id="search_result">
<ul id="tasksUL"/>
</div>
2

2 Answers 2

2

Could you try the following JS and let me know .

<script type="text/javascript">
jQuery.expr[':'].Contains = function(a,i,m){return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;};

$(document).ready(function(){

    var webPartID = $("#WebPartWPQ3");

    $(webPartID).prepend('<div style="padding: 2px; margin: 5px auto 0pt;  display: block;"><h3 style="text-align: left;margin:2px;">Document search: <input type="text" placeholder="Type your text here..."; border: 1px solid rgb(18,105,159); class="search" style="padding: 5px;"/></h3></div>');

        $("input.search").change(function() {
            var txt = $("input.search").val();
            if (txt) {
                $(webPartID).find("td:not(:Contains("+txt+"))").parent("tr.ms-itmhover").hide();
                $(webPartID).find("td:Contains("+txt+")").parent("tr.ms-itmhover").show();
            } else {
                $(webPartID).find("td").parent("tr.ms-itmhover").show();
            }
        }).keyup(function(){$(this).change();
    })
});


</script>
2

I have tried this code and it is worked.

  1. Change the listname to your listname. My current list called TestList.
  2. Change the url. Mine for example i put as example www.contoso.com and replace with your sitecollection url.
  3. Change the column that you want to search. Currently i search using Title
  4. change your result link to the list http://contoso.com/TestList/DispForm.aspx?ID=" + $(this).attr('ows_ID') + "'>"+ $(this).attr("ows_Title") +"</a>
  5. Put all the following script in Script Editor webpart

    <input type="text" style="width:350px" id="txtSearch" />
     <input type="button" style=" font-size:15px;font-family:'Segoe UI Light','Segoe UI','Segoe',Tahoma,Helvetica,Arial,sans-serif; background-color:#0072C6; color:white" id="btnSearch" value="Search" onclick="return search();" />
        <style>
        .highlight {
            background-color: #FFFF88;
        }
        </style>
           <script type="text/javascript" src="https://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
    
    
    
    jQuery.extend({
        highlight: function (node, re, nodeName, className) {
            if (node.nodeType === 3) {
                var match = node.data.match(re);
                if (match) {
                    var highlight = document.createElement(nodeName || 'span');
                    highlight.className = className || 'highlight';
                    var wordNode = node.splitText(match.index);
                    wordNode.splitText(match[0].length);
                    var wordClone = wordNode.cloneNode(true);
                    highlight.appendChild(wordClone);
                    wordNode.parentNode.replaceChild(highlight, wordNode);
                    return 1; //skip added node in parent
                }
            } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
                    !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
                    !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
                for (var i = 0; i < node.childNodes.length; i++) {
                    i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
                }
            }
            return 0;
        }
    });
    
    jQuery.fn.unhighlight = function (options) {
        var settings = { className: 'highlight', element: 'span' };
        jQuery.extend(settings, options);
    
        return this.find(settings.element + "." + settings.className).each(function () {
            var parent = this.parentNode;
            parent.replaceChild(this.firstChild, this);
            parent.normalize();
        }).end();
    };
    
    jQuery.fn.highlight = function (words, options) {
        var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
        jQuery.extend(settings, options);
    
        if (words.constructor === String) {
            words = [words];
        }
        words = jQuery.grep(words, function(word, i){
          return word != '';
        });
        words = jQuery.map(words, function(word, i) {
          return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
        });
        if (words.length == 0) { return this; };
    
        var flag = settings.caseSensitive ? "" : "i";
        var pattern = "(" + words.join("|") + ")";
        if (settings.wordsOnly) {
            pattern = "\\b" + pattern + "\\b";
        }
        var re = new RegExp(pattern, flag);
    
        return this.each(function () {
            jQuery.highlight(this, re, settings.element, settings.className);
        });
    };
    
    </script>
    
    
    <script type="text/javascript">
                function search()
    
              {
    
    
               $("#tasksUL").empty();
              var qry= document.getElementById("txtSearch").value
      var soapEnv =
                "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
                    <soapenv:Body> \
                         <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                            <listName>TestList</listName> \
                            <viewFields> \
                                <ViewFields> \
                                   <FieldRef Name='Title' /> \
     <FieldRef Name='ID' /> \
                               </ViewFields> \
          </viewFields> \
          <query> \
           <Query> \
    <Where> \
    <Contains> \
             <FieldRef Name='Title' /> \
             <Value Type='Text'>"+qry+"</Value> \
          </Contains> \
          </Where> \
    </Query> \
          </query> \
          </GetListItems> \
                    </soapenv:Body> \
                </soapenv:Envelope>";
    
            $.ajax({
                url: "http://contoso.com/_vti_bin/lists.asmx",
                type: "POST",
                dataType: "xml",
                data: soapEnv,
                complete: processResult,
                contentType: "text/xml; charset=\"utf-8\""
            });
    
      }
    
    
    
    
        function processResult(xData, status) {
    // show searching text and image when search button is clicked
    var loadhtml="<div id='loading' class='ms-dlgLoadingTextDiv'><span style='padding-top: 6px; padding-right: 10px;'><img width='24' height='24' title='This animation indicates the operation is in progress. Click to remove this animated image.' src='/_layouts/15/images/gears_anv4.gif?rev=36'/></span><span class='ms-core-pageTitle ms-accentText'>Searching...</span></div>";
    
        var totalRows = parseFloat($(xData.responseXML).find('[nodeName="rs:data"]').attr("ItemCount"));
    if(totalRows=="0")
    {
     $("#loading").remove();
    $("#tasksUL").before("<div  id='loading'  style='color:red;font-size:15px'>No matching records found. Please refine your search.</div>");
    return true;
    }
    $("#tasksUL").before(loadhtml);
            $(xData.responseXML).find("z\\:row").each(function() {
    
    // creating hyperlink for each item to display form of that list item
    var lnk="<a href='http://contoso.com/TestList/DispForm.aspx?ID=" + $(this).attr('ows_ID') + "'>"+ $(this).attr("ows_Title") +"</a>";
    
                var liHtml = "<li>"+ lnk+"</li>";
    
    // 2 second delay and show searching text and image also highlight the result with the searched keyword
    setTimeout(function(){
     $("#loading").remove();
       $("#tasksUL").append(liHtml);
      $("#tasksUL > li").highlight(document.getElementById("txtSearch").value);
    }, 2000);
    
            });
    
        }
    
    $(document).ready(function(){
    // check if enter button is pressed and then search button clicked event is called
        $('#txtSearch').keypress(function(e){
          if(e.keyCode==13)
          $('#btnSearch').click();
        });
    });
    </script>
    // show search result in the ul 
    <div id="search_result">
    <ul id="tasksUL"/>
    </div>
    

You can have a look the post from: http://sharepointerz.blogspot.com.au/2014/05/search-sharepoint-list-items-using.html

3
  • 1
    I changed the name but It searched no output. Here is the info. 1-My list name is Country contacts 2-the link is : my.ABC.org/sites/sandbox1/countryprograms/test/Pages/… and 3-We have 8 fields eg. FName,Lname,Email,...How can I fix . Thanks
    – Sara
    Apr 6, 2017 at 14:43
  • what field you want to search? and can you please put the code that you have so far
    – Supermode
    Apr 12, 2017 at 3:14
  • I sent again could you check it please ?
    – Sara
    Apr 13, 2017 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.