Wednesday, July 4, 2012

.map function


The .map() method is particularly useful for getting or setting the value of a collection of elements.
JQuery.map() can be used when to save as array

var ArrayVal = $('input[name="textbox1[]"]').map(function () { return $(this).val() }).get().join(',');
//the ArrayVal will be comma seperated string

//on retreival part deftn
jQuery.map( arrayOrObject, callback( value, indexOrKey ) )

$.each(ArrayVal, function (key, value) {
alert("key :"+key + " val : " + value);
});


<table>
<tr><td><input type="text" id="txt1" name="textbox1[]" /></td></tr>
<tr><td><input type="text" id="txt2" name="textbox1[]" /></td></tr>
<tr><td><input type="text" id="txt3" name="textbox1[]" /></td></tr>
<tr><td><input type="text" id="txt4" name="textbox1[]" /></td></tr>
</table>

the input type can be either text, checkbox, radio, etc

Friday, June 15, 2012

Radio button change function

/*
if there exist a group of html radio button having same name attribute their click or change can be determined as follows
*/
$("input:radio[name=Test]").change(function () {
    var value = $(this).val();
 });

Inside body tag

<input type="radio" name="Test" value="1"/>
<input type="radio" name="Test" value="2"/>
<input type="radio" name="Test" value="3"/>

Tuesday, June 12, 2012

EXPANDING COLLAPSING DIV

/*
if there a situation that need to have arrange div as blocks/bricks structure then follow this
*/

STEP1:
<link href="../Script/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<script src="../Script/jquery.min.js" type="text/javascript"></script>
STEP2:

<script type="text/javascript">
        $(document).ready(function () {
            $("#expanderHead").click(function () {
                $("#expanderContent").slideToggle();
                if ($("#expanderSign").text() == "+") {
                    $("#expanderSign").html("−")
                }
                else {
                    $("#expanderSign").text("+")
                }
            });
        });
</script>
STEP3:

  <div id="expanderHead" style="cursor: pointer; background-color: Gray; width: 250px;padding-left:10px" class="ui-corner-all">
            EXPANDING COLLAPSING DIV <span id="expanderSign" style="color: Black;font-size:larger"><b>+</b></span>
        </div>
        <div id="expanderContent" style="display: none;padding-left:30px">
            content<br />
            content<br />
            content<br />
            content<br />
            content<br />
        </div>

Expand Collapse (toogle) div


/*
if there a situation that need to have arrange div as blocks/bricks structure then follow this
*/

STEP1:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js" type="text/javascript"></script>
STEP2:
<div class="divHeading">
Heading 1
</div>
<div class="divContent">
contents here 1
</div>
<div class="divHeading">
Heading 2
</div>
<div class="divContent">
contents here 2
</div>

STEP3:
.divHeading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.divContent {
padding: 5px 10px;
background-color:#fafafa;
}

STEP4:
<script type="text/javascript">
$(document).ready(function() {
  $(".divContent").hide();
  //toggle the componenet with class msg_body
  $(".divHeading").click(function()
  {
    $(this).next(".divContent").slideToggle(500);
  });
});
</script>

Wednesday, May 30, 2012

File Upload

PAGE1.aspx
 <img src="../images/upload-new.png" title="Upload New Documents" id="TestNewUpload"
style="cursor:pointer; margin-left:870px;" href="PAGE2.aspx"/>


$("#TestNewUpload").live('click', function (e) {

            var page = $(this).attr("href")
            page += "?ID=" + TestID + "&Type =" +1;
            var $dialog = $('<div></div>')
                .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                .dialog({
                    autoOpen: false,
                    modal: true,
                    height: 450,
                    width: 600,
                    title: "Upload document",
                    buttons: {
                        "Close": function () {
                            $dialog.dialog('close');
                        }
                    },
                    close: function (event, ui) {
                    }
                });
            $dialog.dialog('open');
            e.preventDefault();
        }); 

PAGE1 END

PAGE2.aspx
<form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <Triggers>
                <asp:PostBackTrigger ControlID="btnUpload" />
            </Triggers>
            <ContentTemplate>
                <div id="divUpload" runat="server">
                    <table>
                        <tr><td>Title</td><td>
<asp:TextBox ID="txtTitle" runat="server" MaxLength="99"></asp:TextBox>
                            </td></tr>
                        <tr><td>Document</td>
                            <td><asp:FileUpload ID="fuTestUploads" runat="server" /></td></tr>                       
                        <tr><td></td>
                            <td>
          <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
                            </td></tr>
                    </table>
                </div>
                <div id="divMessage" runat="server" class="centered">
                    <center>
                        <span style="font-weight:bold; font-size:15px;"> Document uploaded successfully! </span>
                    </center>
                    <br />
                    <asp:LinkButton ID="lbtnUploadMore" runat="server"
                        onclick="lbtnUploadMore_Click">Upload More</asp:LinkButton>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
        <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
            <ProgressTemplate>
                <div class="centered">
                    <img src="../images/ajax-loader.gif" alt="" />
                    &nbsp; Please wait...
                </div>
            </ProgressTemplate>
        </asp:UpdateProgress>
    </div>
    </form>

//ASPX.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.AccessControl;

namespace TESTUI
{
    public partial class PAGE2: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                divMessage.Visible = false;
                trDiscipline.Visible = false;
                int RegulationType = Convert.ToInt32(Request.QueryString["RegulationType"].ToString());
                if (RegulationType == 3)
                {
                    trDiscipline.Visible = true;
                }
            }
        }

        private void DisplayMessage(string msg)
        {
            string strText = "alert('" + msg + "')";
            string myScript = String.Format(strText);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "MyScript", myScript, true);
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (!fuTestUploads.HasFile)
            {
                return;
            }
            int TestID = Convert.ToInt32(Request.QueryString["TestID"].ToString());
            int Type = Convert.ToInt32(Request.QueryString["Type"].ToString());
           

            string Title = txtDocumentTitle.Text;
            string FileName = System.IO.Path.GetFileName(fuTestUploads.FileName);
            string Extension = System.IO.Path.GetExtension(fuTestUploads.PostedFile.FileName);
            int Size = fuTestUploads.PostedFile.ContentLength;

            ServiceReference1.OFRTWCFServiceClient Proxy = new ServiceReference1.OFRTWCFServiceClient();

            int FileID = Proxy.AddDocument(Title, Type, FileName, Extension, Size, TestID);

            if (FileID != 0)
            {
                string path = Server.MapPath( "~/files/" + FileID.ToString());
               
                //DirectorySecurity scr = new DirectorySecurity(AppDomain.CurrentDomain.BaseDirectory.ToString(), AccessControlSections.All);
                System.IO.Directory.CreateDirectory(path);
                fuRegulationsUploads.PostedFile.SaveAs(path + "/" + fuTestUploads.PostedFile.FileName);
                txtDocumentTitle.Text = string.Empty;
                divUpload.Visible = false;
                divMessage.Visible = true;
            }
        }

        protected void lbtnUploadMore_Click(object sender, EventArgs e)
        {
            divUpload.Visible = true;
            divMessage.Visible = false;
        }
    }
}
PAGE2 END

Tuesday, May 29, 2012

File Download

To download a file
1. Create a new aspx page and code as follows


//TEST.ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestFileDownload.aspx.cs" Inherits="TESTUI.TestFileDownload" %>


//TEST.ASPX.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Threading;

namespace TestUI
{
    public partial class TestFileDownload: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string FileId = Request.QueryString["FileID"].ToString();
            string FileName = Request.QueryString["FileName"].ToString();
             
            string path = Server.MapPath( "~/files/" + FileId + "/" + FileName);

            fileDownload(FileName, path);

        }

        private void fileDownload(string fileName, string fileUrl)
        {
            Page.Response.Clear();
            bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
            if (!success)
                Response.Write("Downloading Error!");
            Page.Response.End();

        }
        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    int pack = 10240; //10K bytes
                    int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                 
                    _Response.ContentType = "application/octet-stream";
                    _Response.ClearContent();
                    _fileName = _fileName.Replace(" ", "");
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + _fileName);

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(pack));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}



2. Pass Parameters ie FileID and FileName to download

var FileID = 1;
var  FileName = "TestFileName";
 FileName = FileName.replace(/&/g, "%26");

window.open('../TestFileDownload.aspx?FileID=' + FileID + '&FileName=' + FileName, '_blank');

Open a new page as Popup

 var page = "../TestPage.aspx";
  page += '?ID=' + TestID + '&ProjID=' + Pid ;

var $dialog = $('<div></div>')
                .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                .dialog({
                    autoOpen: false,
                    modal: true,
                    height: 700,
                    width: 1200,
                    title: "Upload Documents For " + Upload,
                    buttons: {
                        "Close": function () {
                            GetDetails();
                            $dialog.dialog('close');
                        }
                    },
                    close: function (event, ui) {
                        GetDetails();
                    }
                });
            $dialog.dialog('open');
            e.preventDefault();



//Call this on a button click

Delegate

$("#divTest").delegate('table select', 'change', function () {
       var tempddl1 = $(this).parent().find("select option:selected").eq(0).text();
       var tempddl2 = $(this).parent().find("select option:selected").eq(1).text();
       alert("do something");
});


<div id="divTest">
<table><tr><td>
<select>
<option>One</option>
<option>Two</option>
</select>
Some seperation
<select>
<option>One1</option>
<option>Two1</option>
</select>

</td></tr></table>

<table><tr><td>
<select>
<option>One</option>
<option>Two</option>
</select>
 Some seperation
<select>
<option>One1</option>
<option>Two1</option>
</select>
</td></tr></table>
</div>


//to do an action on the change of any SELECT inthe parent DIV
//use delegate

Friday, May 25, 2012

Clone Function

1. USE JS
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>

2. INSIDE DOCUMENT.READY
//START 2
//NEW CLONED ELEMENT ADDED ON CLICKING
 $("#imgAdd").click(function () {
        $("#tblTest").find("tr:last").after($("#tblTest").find("tr:last").clone());
        //IF YOU WANT TO FILL NEWILY CLONED THING WITH A TEXT
         //$("#tblTest").find("tr:last").find("input:text").val("hello test");
  });
// REMOVING LAST ADDED ITEM
 $("#imgRemove").click(function () {
            if ($("#tblTest").find("tr:first").nextAll().length >= 1) {
                 $("#tblTest").find("tr:last").remove();
             }
 });
 //END 2
//IF TO REMOVE ALL CLONED ELEMENTS USE
 //$("#tblTest").find("tr:first").remove();


3. ON THE BODY TAG
  <table id="tblTest">
        <tr>
            <td>
                Your text here &nbsp;<input type="text" />            </td>
        </tr>
    </table>
    <img alt="" src="../Images/add.gif" id="imgAdd"/>
    <img alt="" src="../Images/remove.png" id="imgRemove"/>

Multiple Scroll

1. USE THE JS FILE
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>

2. DOCUMENT.READY

 <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#cbxScroll").click(function () {
                if ($('#cbxScroll').attr('checked')) {                   
                    window.setInterval("checkScroll(document.getElementById('divLeft'), document.getElementById('divRight'))", 1);
                }
                else {
                    window.setTimeout('location.reload()', 10);
                }
            });
        });

        // Multiple Scroll - START
        var lastSeen = [0, 0];
        function checkScroll(div1, div2) {
            if (!div1 || !div2) return;
            var control = null;
            if (div1.scrollTop != lastSeen[0]) control = div1;
            else if (div2.scrollTop != lastSeen[1]) control = div2;
            if (control == null) return;
            else div1.scrollTop = div2.scrollTop = control.scrollTop;
            lastSeen[0] = div1.scrollTop;
            lastSeen[1] = div2.scrollTop;
        }
        // Multiple Scroll - END
    </script>

3. INSIDE BODY TAG

<div id="divScroll" style="margin-left: 1100px">
        <input id="cbxScroll" type="checkbox" />Enable Multiple Scroll
</div>

 <div style="width: 1100px;">
        <div id="divLeft" style="width: 500px; height: 100px; border: groove gray; float: left;
            overflow: scroll">
            ssss<br />
            aaaa<br />
            cccc<br />
            dddd<br />
            zzzz<br />
            eeee<br />
            qqqq<br />
            xxxx
        </div>
        <div id="divRight" style="width: 500px; height: 100px; border: groove gray; float: left;
            margin-left: 10px; overflow: scroll">
            ssss<br />
            aaaa<br />
            cccc<br />
            dddd<br />
            zzzz<br />
            eeee<br />
            qqqq<br />
            xxxx
        </div>
    </div>

Monday, May 14, 2012

ul-li style

<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
  • One
  • Two
  • Three

if to remove these bullets, add style
ul
{
list-style-type: none;
}

One
Two
Three

To arrange these in vertical
li
{
float:left;
}

Wednesday, March 28, 2012

Converting to XML Format Variable

Suppose there exists a lot of Checkboxes, for saving all we can convert values to an XML format and pass to DB

<div id="divTest">
<table>
<tr>
<td>
<input type="checkbox" value="1"/>One
</td>
<td>
<input type="checkbox" value="2"/>Two
</td>
</tr>
<tr>
...................
...................
</tr>

</table>
</div>

--------------------------------

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>

<script type="text/javascript" language="javascript">
$(document).ready(function () {

$("btnSave").click(function(){
                 var TestXML = "<STHome>";
                $("#divTest").find("input:checkbox").each(function () {
                    if ($(this).attr("checked")) {
                        TestXML = TestXML + "<Home>";
                        TestXML = TestXML + "<ID>" + $(this).val() + "</ID>";                                               
                        TestXML = TestXML + "<TestValue>" + "" + "</TestValue>";                  
                        TestXML = TestXML + "</Home>";
                    }
                });
                TestXML = STHomeXML + "</STHome>";
        $.ajax({
                     type: "POST",
                      url: "TestPage.aspx/InsertDetails",
                      dataType: "json",
                      data: "{'TestID':'" + TestID + "','TestXML':'" + TestXML + "'}",
                      contentType: "application/json; charset=utf-8",
                      success: function (result) {
                alert("save successfully");
            }
        });
  });//Button Click end

});//document.ready end
</script>


------------

and pass this "TestXML" variable to aspx.cs
Go to sareeshmg.blogspot.com
post name : XML Insert

Tuesday, March 27, 2012

Validations

USE Jquery files
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>



//Check the Full Name,dot and space are allowed
function Validate_NameFull(Name) {
    reg = new RegExp("^[a-zA-Z .]*$");
    var Result = true;
    if (!(Name.match(reg))) {
        Result = false;
    }
   return Result;

}
//Check the First Name,space not allowed
function Validate_NameFirst(Name) {
    reg = new RegExp("^[a-zA-Z]*$");
    var Result = true;
    if (!(Name.match(reg))) {
        Result = false;
    }
    return Result;
}
//Check Number valid or not
function Validate_Number(Number) {
   var reg = new RegExp("^[0-9]*$");
    var Result = true;
    if (!(Number.match(reg))) {
        Result = false;
    }
    return Result;
}
function Validate_Email(Email) {
    var pattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var Result = true;
    if (!(Email.match(pattern))) {
        Result = false;
    }
    return Result;
}
function Validate_Phone(Phone) {
    var pattern = /^[0-9 + -]*$/;
    var Result = true;
    if (!(Phone.match(pattern))) {
        Result = false;
    }
    return Result;
}
function Validate_Mobile(Mobile) {
    var pattern = /^([9]{1})([234789]{1})([0-9]{8})$/;
    var Result = true;
    if (!(Mobile.match(pattern))) {
        Result = false;
    }
    return Result;
}
function Validate_Date(Date) {
    var pattern = /^\d{1,2}\-\d{1,2}\-\d{4}$/;
    var Result = true;
    if (!(Date.match(pattern))) {
        Result = false;
    }
    return Result;
}
function Validate_Website(Web) {

    var pattern = /^www+\.([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
 
    var Result = true;
    if (!(Web.match(pattern))) {
        Result = false;
    }
    return Result;
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 43 || charCode > 57))
        return false;

    return true;
}
function isQuotesKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode == 39 || charCode == 96 || charCode == 34 || charCode == 58 || charCode == 59 || charCode == 126)
        return false;

    return true;
}


---------------
EG:
<input type="text" id="txtPrimaryNo" onkeypress="return isNumberKey(event)" />

Query String

EG :
url : http://www.sareeshmg.blogspot.com?id=2"


<script language="javascript" type="text/javascript">
        function getQueryParams(qs) {
            qs = qs.split("+").join(" ");
            var params = {};
            var tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;
            while (tokens = re.exec(qs)) {
                params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
            }
            return params;
        }

        var $_GET = getQueryParams(document.location.search);

//To Capture query string value at aspx page use like this
        var TestID = $_GET['id'];

</script>

---------------------
ON Code behind aspx.cs page
to capture query string ID

int TestID = Convert.ToInt32(Request.QueryString["id"].ToString());

Enter Key event

$("#txtPassword").keyup(function (event) {
        if (event.keyCode == 13) {                  
            $("#btnSignIn").click();      
         }        
  });

Open a new Page on another or same tab

To open in a new tab
window.open('TestPage.aspx', '_blank');
OR
window.open('TestPage.aspx', '_blank',, "width=400,height=200,menubar=no,toolbar=no" );



To open in the same tab
window.location = "TestPage.aspx";

Friday, March 2, 2012

Jquery checkbox Groups (Select one checkbox from a group)

$(document).ready(function() {

          $(".selector input.testcheck").click(function () {
                var test = $(this).val();
             
              if ($(this).attr("checked")) {
                  $(".selector input.testcheck[value!=" + test + "]").attr('checked', false);
                  $(".selector input.testcheck[value=" + test + "]").attr('checked', true);
               }
                else {
                    $(this).removeAttr("checked")
                }
            });

 });
----------------------------------
<div class="selector">
<input type="checkbox" name="cbxtest" value="1" class="testcheck"/>YES                         
<input type="checkbox" name="cbxtest" value="2" class="testcheck"/>NO
  </div>

Thursday, February 23, 2012

Slider Control

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
    <link href="../Scripts/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $("#txtTest").text("0");
            $(function () {
                $("#sliderTest").slider({
                    range: "max",
                    min: 0,
                    max: 10,
                    value: 0,
                    slide: function (event, ui) {
                        $("#txtTest").text(ui.value);

                        if (ui.value > 4) {
                            alert("hi");
                        }
                        else {
                            alert("hi123");
                        }
                    }
                });
            });
        });
    </script>


--------------

 <div id="sliderTest"></div>
        <br />
<label id="txtTest"></label>

Wednesday, February 22, 2012

Prevent Cut Copy Paste

 $('#txtNotes').bind('cut copy paste', function (event) {
                event.preventDefault();
            });

TextArea remaining characters showing

---------------------------------------------------------
                                   TYPE : 1
---------------------------------------------------------

<script type="text/javascript" language="javascript">

 function textCounter(field, countfield, maxlimit) {
            if (field.value.length > maxlimit) {
                field.value = field.value.substring(0, maxlimit);
                alert('Textarea value can only be 20 characters in length.');
                return false;
            }
            else {
                countfield.value = maxlimit - field.value.length;
            }
        }
</script>




<textarea rows="10" cols="80" id="txtNotes" style="resize: none" onkeypress="textCounter(this,this.form.counter,20);"></textarea>
<input type="text" name="counter" maxlength="5" size="3" value="20" onblur="textCounter(this.form.counter,this,20);" />
                            chars remaining


-----------------------------------------------------------------------
                                           TYPE : 2
-----------------------------------------------------------------------

function countDown(control, maxLen, counter, typeName) {
    
var len = control.value.length;
    
var txt = control.value;
    
var span = document.getElementById(counter);
     span.style.display = '';
     span.innerHTML = (maxLen - len) + ' characters remaining';
    
if (len >= (maxLen - 10)) {
          span.style.color = 'red';
         
if (len > maxLen) {
               control.innerHTML = txt.substring(0, maxLen);
               span.innerHTML = (maxLen - control.value.length) + ' characters remaining';
               alert(typeName + ' text exceeds the maximum allowed!');
          }
     } 
else {
          span.style.color = '';
     }
}





<textarea id="Description" onkeyup="countDown(this, 255, 'desc', 'Description');"></textarea>


<SPAN id="desc" style="DISPLAY: none">255 characters remaining</SPAN>




-----------------------------------------------------------------
                                 TYPE : 3
-----------------------------------------------------------------

<script type="text/javascript" language="javascript">
        var len = 0;
        var characterLimit = 3492;

        $(document).ready(function () {


            //check for max length of a textarea START
            $("#divremainingChar").hide();
            $("#txtNotes").keydown(function (event) {
                len = $("#txtNotes").val().length;
                len += 1;

                var charactersRemaining = characterLimit - len;

                if (len >= characterLimit) {
                    // Allow only backspace and delete
                    if (event.keyCode == 46 || event.keyCode == 8) {

                    }
                    else {
                        event.preventDefault();
                    }
                }
                $("#divremainingChar").show();
                $('#remainingCharacters').html(charactersRemaining);
            });
            //check for max length of a textarea END

</script>



 <textarea cols="100" rows="10" id="txtNotes"></textarea>
                        <br />
                       <div style="color:Gray" id="divremainingChar"> <span id="remainingCharacters" ></span> characters remaining.  </div>

Setting up Maxlength for TEXTAREA

TYPE : 1

<script type="text/javascript" language="javascript">
 function SetMaxLength(Object, MaxLen) {
            return (Object.value.length <= MaxLen);
        }
</script>


<textarea rows="10" cols="80" id="txtNotes" style="resize: none" onkeypress="return SetMaxLength(this, 15);"></textarea>

//style="resize: none" will make textarea fixed size
-----------------------------------------------------

TYPE : 2


function textLimit(field, maxlen) {
            if (field.value.length > maxlen) {
                while (field.value.length > maxlen) {
                    field.value = field.value.replace(/.$/, '');
                }
                alert('Maximum limit exceeded!');
            }
        }


<textarea rows="10" cols="80" id="txtNotes" style="resize: none" onkeypress="textLimit(this,20)"></textarea>

To find radio button text and value

$("#btnTest").click(function () {

            $("#divTestFunction").find("table").find("tr").each(function () {
                $(this).find("input:radio").each(function () {
                    if ($(this).attr("checked") == true) {                      
                        alert(jQuery.trim($(this).parent().text()));
                    }
                });
            });
 });

-----------------------------------------

<div id="divTestFunction">
        <table>
            <tr>
                <td>
                </td>
                <td>
                    <input type="radio" name="rbtnTest" />Demo Text
                </td>
            </tr>
        </table>
    </div>
    <input type="button" id="btnTest" value="Test" />

Tuesday, January 17, 2012

To get select radiobutton value using its name

Use like this

$('input:radio[name=radReason]').change(function() {
  varSelval = $("input:radio[name=radReason]:checked").val();
});

Friday, January 13, 2012

Hide/Remove dialogbox close button in title

closeOnEscape: false,
open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); },

------------------
$("#popUpOne").dialog({
                autoOpen: false,
                height: 660,
                width: 740,
                modal: true,
                closeOnEscape: false,
                open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); },
                buttons: {
                    "SAVE": function () {
                        SaveFunction();
                    },
                    CANCEL: function () {
                        $(this).dialog("close");
                    }
                },
                close: function () {
                    allFields.val("").removeClass("ui-state-error");
                }
            });

Wednesday, January 11, 2012

Auto Complete textbox

------------------------ASPX PAGE--------------------------------
var AutoTestID = 0;
$(document).ready(function(){


        $("#txtTestName").autocomplete({
                source: function (request, response) {
                    TestID= 0;
                    $.ajax({
                        url: "ReferalIntakeOrg.aspx/GetPatientNameAutoSugg",
                        data: "{ 'TestName': '" + request.term + "','PhoneNo':'"+ $("#txtPrimaryNo").val()+"'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.Name,
                                    value: item.Name,
                                    Id: item.Id
                                }
                            }))
                        }
                    });
                },
                minLength: 1,
                select: function (event, ui) {
                    AutoTestID= ui.item.Id;
                    FillTestDetails(AutoTestID);
                }
            });
}); //document.ready ends here




--------------ASPX.CS PAGE----------------
[WebMethod]
        public static List<AutoFillItem> GetPatientNameAutoSugg(string PatientName, string PrimaryContactNo)
        {
            List<AutoFillItem> list = new List<AutoFillItem>();
            ServiceReference1.TestWCFServiceClient oITestWCFService = new ServiceReference1.TestWCFServiceClient();
            DataSet ds = oITestWCFService.GetTestNameAutoSugg(TestName, PhoneNo);

            foreach (DataRow tr in ds.Tables[0].Rows)
            {
                AutoFillItem item = new AutoFillItem();
                item.Id = tr[0].ToString();
                item.Name = tr[1].ToString();

                list.Add(item);
            }
            return list.ToList();
        }

------------------------ADD A CLASS AutoFillItem.cs------------------
//declare our needs
 public string Id;
 public string Name;

Add days to selected date


 $('#txttFrom').change(function () {
                var date2 = $('#txtFrom').datepicker('getDate', '+1d');
                date2.setDate(date2.getDate() + 60);
                $('#txtTo').datepicker('setDate', date2);
            });

------------OR--------------
  $('#txtDate').datepicker({ onSelect: function (dateStr) {
            var date = $(this).datepicker('getDate');
            if (date) {
                date.setDate(date.getDate() + 1);
                // Do something with date + 1
            }
        }
        });

Wednesday, January 4, 2012

Parent Child Selector

The syntax for finding children which are direct descendants of an element looks like this:

$("div > a")

This selector will find all links which are the direct child of a div element. Replacing the greater-than symbol with a simple space will change this to match all links within a div element, no matter if they are directly related or not:

$("div a")

eg : 

<div id="divTest1">
        <b>Bold text</b>
        <i>Italic text</i>
        <div id="divTest2">
                <b>Bold text 2</b>
                <i>Italic text 2</i>
                <div>
                        <b>Bold text 3</b>
                </div>
        </div>
</div>
<script type="text/javascript">

$("#divTest1 > b").css("color", "blue");
</script>
 
 
************************
 //here  bold tags blue if they are directly descending from the divTest1:
$("#divTest1 > b").css("color", "blue");
 
// //here  all the bold tags colour green within the divTest1:
$("#divTest1  b").css("color", "green");