Pages

Monday, May 23, 2011

Autocomplete using post jquery ajax

Invoke a non postback model for Autocomplete using jquery ajax.
http://docs.jquery.com/UI
Example of Autocomplete can be found on  SapSite
  • Download the 'jQuery UI 1.8.9' and the related jquery ui css.
  • Create a new .Net solution and copy in global/ui/js directory.
  • In your default.aspx page add references to 
<script type="text/javascript" src="/global/ui/js/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="/global/ui/css/jquery-ui.css" />

  • Add this to the default page.
<form id="searchsite" class="search" title="Search" method="post" action="search-results.aspx">

<script language="javascript" type="text/javascript">
 $('#textbox1').autocomplete({
        minLength: 0,
        delay: 0,
        source: function (request, respond) {
            get_suggestions(request.term, function (response) {
                respond(eval(response))
            });
        },
        select: function (event, ui) {
            $('#textbox1').val(ui.item.value);
            $('#searchbutton').submit();
        }
    });
 
function get_suggestions(payload, ok_handler) {
    $.post(
            your_service_url,
            function (data) {
                if (ok_handler) ok_handler(data);
            },
            function (e) {
                alert(e);
            }
        );
}
</script> 
  • If you want to highlight the letters typed in the list then you need to hack 
    the _render function inside jquery-ui.js.
    Just replace the renderItem function with this function.
_renderItem: function( ul, item) {
          item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + 
$.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)""gi"), 
"<strong>$1</strong>");
            return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a>" + item.label + "</a>")
                    .appendTo(ul);
      },  

No comments: