Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Wednesday, December 17, 2014

checkboxlist/radiobuttonlist filter textbox using jQuery (with result count)

Hi Developers,

following is the complete single code to filter large list of checkboxes and radiobuttons. I created a hashtable and bind that to radiobuttonlist and checkboxlist. we can use any data source(collection, dataset, datatable etc) instead. same code will work with other data listing controls(repeater, datalist and gridview).

test.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test1.aspx.cs" Inherits="test1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>nitindhiman.blogspot.com</title>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    function textChange(e, txtbox, cls) {
      if (!(/[^A-Za-z0-9 ]/.test(String.fromCharCode(e.keyCode))) || e.keyCode == 8) {
        var text = $(txtbox).val().toLowerCase();
        var node = '';
        var count = 0;
        $('#td_' + cls + ' table tr').each(function () {
          node = $(this).text().toLowerCase();
          if (node.match(text) == null)
            $(this).hide();
          else {
            $(this).show();
            count++;
          }
        });
        $('#sp_' + cls).html((count) + ' items');
      }
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <table>
        <tr>
          <td >
            <asp:TextBox ID="txtChkFilter" runat="server" onkeyup="javascript:textChange(event,this,'Chk');"></asp:TextBox>
            <span id="sp_Chk"><%=ChkCount%></span>
          </td>
          <td >
            <asp:TextBox ID="txtRadioFilter" runat="server" onkeyup="javascript:textChange(event,this,'Rdo');"></asp:TextBox>
            <span id="sp_Rdo"><%=RdoCount%></span>
          </td>
        </tr>
        <tr>
          <td>
            <div id="td_Chk">
              <asp:CheckBoxList ID="cblChkOption" DataValueField="Key" DataTextField="Value" runat="server">
              </asp:CheckBoxList>
            </div>
          </td>
          <td>
            <div id="td_Rdo">
              <asp:RadioButtonList ID="cblRdoOption" DataValueField="Key" DataTextField="Value" runat="server">
              </asp:RadioButtonList>
            </div>
          </td>
        </tr>
      </table>
    </div>
  </form>
</body>
</html>

test.aspx.cs

using System;
using System.Collections;

public partial class test1 : System.Web.UI.Page
{
    protected string ChkCount = string.Empty;
    protected string RdoCount = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        binddate();
    }
    void binddate()
    {
        Hashtable ht = new Hashtable();
        ht.Add(1, "System");
        ht.Add(2, "Collections");
        ht.Add(3, "Generic");
        ht.Add(4, "Linq");
        ht.Add(5, "Web");
        ht.Add(6, "UI");
        ht.Add(7, "WebControls");
        ChkCount = ht.Count + " items";
        RdoCount = ht.Count + " items";
        cblChkOption.DataSource = ht;
        cblChkOption.DataBind();
        cblRdoOption.DataSource = ht;
        cblRdoOption.DataBind();
    }
}

Wednesday, January 16, 2013

JAVASCRIPT Validation by css class


function validate(matchClass) {
var reg = new RegExp("^[a-zA-Z0-9 *]*$");
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if ((" " + elems[i].className + " ").indexOf(" " + matchClass + " ") > -1) {
if (reg.test(elems[i].value) == false) {
alert('Please enter a valid search keyword');
elems[i].value = "";
elems[i].focus();
return false;}}}
return false;}

Monday, September 20, 2010

javascript to change validation group name

change group name :

Monday, July 26, 2010

Handle Exception in Update panel(asp.net Ajax and Error/Exception Handling)

Problem: While using Ajax with asp.net, if we get crash on any event which was fired by a control in a update panel we do not get any yellow screen or error page. And end user does not get any message or result.

Solution:
Step-1: Add OnAsyncPostBackError event to the script manager and set AllowCustomErrorsRedirect property to true.

<asp:scriptmanager allowcustomerrorsredirect="true" id="smBody" onasyncpostbackerror="smBody_AsyncPostBackError" runat="server"></asp:scriptmanager>

Step-2: Add the following script after the script manager(Otherwise you will get javascript error on the page).

<script type="text/javascript">
      Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
</script>
Step-3: Add the following script to the page:
<script type="text/javascript">
    function EndRequestHandler(sender, args) {
      if (args.get_error() != undefined) {
        var Error = "Error Code: " + args.get_response().get_statusCode() + "\nError Message: " +
                    args.get_error().message;
        alert(Error);
        args.set_errorHandled(true);
        //Uncomment the following line to refresh the window after alert the error message.
        //window.location = window.location;
      }
    }
  </script>
Step-4: Write the script-manager's AsyncPostBackError event:
protected void smBody_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
smBody.AsyncPostBackErrorMessage = e.Exception.Message;
}
Now all the postback errors will be displayed in alert message and after that the page will be reloaded :-).
Thanks. :-)

Tuesday, July 6, 2010

ajax post to post data to server and get response using jQuery and JSON.

1. Create a page PageName.aspx, create a div on that:
    <div id="target_div_id">  

    </div>
2. Include the jQuery file.
3. call the following javascript function on any event:
function JsonPost(input1, input2, input3, input4) {

        URL = "PageName.aspx/WebMethodName";

    var options = {

        type: "POST",

        contentType: "application/json; charset=utf-8",

        dataType: "json",

        url: URL,

        data: '{input1:"' + input1 + '", input2:"' + input2 + '", input3:"' + input3 + '", input4:"' + input4 + '"}',

        success: function (msg) {

            if (msg.d == 'error')

                alert(msg.d);

            else {

                $('#target_div_id').append(msg.d);

            }

            HideLoader();

        },

        error: function (msg) {

            alert(msg.d);

        }

    };

    $.ajax(options);

}
4. Following web method will automatically called:


    /// <summary>

    /// Create a web method, input parameter must be same as the parameters in our web method.

    /// from here we will have to return the complete html(including html controls, their ids and classes)

    /// </summary>

    /// <param name="input1"></param>

    /// <param name="input2"></param>

    /// <param name="input3"></param>

    /// <param name="input4"></param>

    /// <returns></returns>

    [WebMethod]

    public static string WebMethodName(string input1, string input2, string input3, string input4)

    {

        try

        {

            int j = 10;//some number depending upon our requirement

            StringBuilder sbResult = new StringBuilder();

            for (int i = 0; i < j; i++)

            {

                sbResult.AppendLine("<!--any required html containing controls and ids-->");

            }

            return sbResult.ToString();

        }

        catch (Exception ex)

        {

            return ex.Message;

        }

    }

Monday, March 29, 2010

Casecading dropdown using JQuery.

1) Put the following JavaScript function on the page:

function BindDropDown(dropdown_parent,dropdown_child,selectedVal)
{
if(document.getElementById(dropdown_parent).selectedIndex>0)
{
$.ajax
({
url: "/GetAjaxData.aspx",
data: "type=products&value="+document.getElementById(dropdown_parent).options[document.getElementById(dropdown_parent).selectedIndex].value,
success: function(message1)
{
var selectedindex=0;
var rows1 = message1.split("\n");
var iCount = 0;
document.getElementById(dropdown_child).options.length = 0;
for (iCount = 0; iCount < rows1.length; iCount++)
{
var valu=rows1[iCount].split("|");
if(valu[1].replace(/^\s*/, "").replace(/\s*$/, "")==selectedVal)
selectedindex=iCount;
var oOption = new Option(valu[0],valu[1].replace(/^\s*/, "").replace(/\s*$/, ""));
document.getElementById(dropdown_child).options.add(oOption);
}
document.getElementById(dropdown_child).options[selectedindex].selected=true;
return false;
}
});
}
else
{
document.getElementById(dropdown_child).options.length = 0;
document.getElementById(dropdown_child).options.add(new Option("--Select--", "0"));
}
}

2) Call The Following function on dropdown's selected index change:


 BindProducts('<%=ddlParent.ClientID%>', '<%=ddlChild.ClientID%>', '<%=Id%>')


3) Put the following code on the GetAjaxData.aspx page:

protected void Page_Load(object sender, EventArgs e)
{
ReturnDDLData(Convert.ToInt32(Request.QueryString["value"]));
}
private void ReturnDDLData(Int32 selectedId)
{
Response.Clear();
StringBuilder sbResponse = new StringBuilder();
Collection m_oCollection = new Collection();
m_oCollection.GetCollection(selectedId);
sbResponse.Append(string.Concat("--Select--", "|0", Environment.NewLine));
foreach (Product m_oItem in m_oCollection)
{
sbResponse.Append(string.Concat(m_oItem.Name, "|", m_oItem.ID.Value.ToString().Trim()) + Environment.NewLine);
}
Response.Output.Write(sbResponse.ToString().Substring(0, sbResponse.ToString().LastIndexOf(Environment.NewLine)));
Response.End();
}

Friday, February 26, 2010

Custom Validator in JQuery.Validate

$.validator.addMethod(
"regexName",
function(value, element) {
var check = false;
var re = new RegExp('^[a-zA-Z _0-9.]+$');
return this.optional(element) || re.test(value);
},
"No special characters allowed!"
);


rules: {
LoginName: {
required: true,
regexName:true
},

Open fancybox on Input Click

1)
$(document).ready(function()
{
$("#BTN").click(function()
{
$('test desc').fancybox().click();
});
});


2)

$("#buttontoclick").click(function() {
$('Friendly description').fancybox({
overlayShow: true
}).click();
});


3)

        function OpenPage(id) {
            $('dummy_anchor').fancybox({
                'frameWidth': 420, 'frameHeight': 413 // 'frameHeight': 232
            }).click();
        }

JS file with Server Side Variable

Javascript object and class concept

<_script_start>
var path = {
currentUrl: "",
getPath: function() {
return this.currentUrl;
},
TEST: function() {
alert(this.currentUrl);
}
}

script type="text/javascript">
path.currentUrl = '';
path.TEST();