Monday, December 29, 2014

asp.net, jQuery: Search feature, Search with enter button click.

Following example will demonstrate the search functionality in asp.net page using jQuery. This will also work with enter button click:

<asp:Panel ID="Panel1" runat="server" DefaultButton="btnSearch">
<table style="width:100%;">
  <tr>
    <td style="vertical-align: top;">
      <input class="form-control" id="txtSearch" type="text" placeholder="Search.." /></td>
    <td style="width:35px;">
      <asp:ImageButton ID="btnSearch" ImageUrl="Images/search-icon.png"
        OnClientClick="javascript:return Search('txtSearch');" runat="server" />
    </td>
  </tr>
</table>
</asp:Panel>
Please Note: asp:Panel is used here to make functionality working with enter button click, that is why we have to take asp:ImageButton instead of any normal html button.
Following JavaScript Code will navigate to search page.

<script type="text/javascript">
    function Search(txtbox) {
        var pat = new RegExp('^([0-9a-zA-Z _]+)$');
        if (!pat.test($('#' + txtbox).val())) {
            alert('Please enter valid keyword to search');
            return false;
        }
        var value = $('#' + txtbox).val().replace(" ", "_");
        if (value == 'SEARCH') {
            alert('Please enter keyword to search');
            return false;
        }
        else if ($.trim(value) == '') {
            window.location = '<%=ReadConfig.SiteUrl %>Search.aspx?q=' + value;
        }
        else {
            window.location = '<%=ReadConfig.SiteUrl %>AllSearch.aspx';
        }
        return false;
    }
</script>

This will also check special characters in search field.

No comments:

Post a Comment