Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Friday, 21 March 2014

JQPlot Charts

To use JQPlot Charts first download JQPlot JQuery plugins from http://www.jqplot.com/

now copy the required js files from plugin to your project and add the script as follows. This script is as per my requirement so yours logic and code can differ from mine.

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.jqplot.min.js"></script>
<link href="~/Content/Styles/jquery.jqplot.css" rel="stylesheet" />
<script src="~/Scripts/jqplot.barRenderer.min.js"></script>
<script src="~/Scripts/jqplot.categoryAxisRenderer.min.js"></script>
<script src="~/Scripts/jqplot.pointLabels.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
 BindChart();   
 }

 function BindChart() {
        try {
   var Projects = "";
        $(".chk").each(function () {
            if ($(this).is(':checked'))
                Projects += $(this).val() + ",";
        });
        var ProjectList = Projects.substring(0, Projects.length - 1);
        var Criteria = $("#ddlCriteria").val();
        var From = "", To = "", Title = "";;
        var Tenure = $("#ddlTenure").val();
        var FromYear, FromMonth, ToYear, ToMonth;
        if (Tenure == "Monthly") {
            From = $("#ddlFrom").val();
            To = $("#ddlTo").val();
            FromYear = From.toString().substring(0, 4);
            FromMonth = From.toString().substring(4, 6);
            ToYear = To.toString().substring(0, 4);
            ToMonth = To.toString().substring(4, 6);
            //Title = "(Period " + $("#ddlFrom").val() + "-" + $("#ddlTo").val() + ")";
            Title = "";
        }

           var ChartData = new Array();
           $.getJSON("../Dashboard/DelayedMilestoneChartData", { Criteria: Criteria, FromYear: FromYear, FromMonth: FromMonth, ToYear: ToYear, ToMonth: ToMonth, ProjectList: ProjectList }, function (temp) {
                if (temp != null || temp != undefined || temp != "") {
                    for (var m = 0; m < temp.Month.length; m++) {
                        var MonthWiseData = new Array()
                        for (var c = 0; c < temp.Company.length; c++) {
                            var flag = 0;
                            for (var i = 0; i < temp.Data.length; i++) {
                                if (temp.Data[i].Month == temp.Month[m] && temp.Data[i].CustomerName == temp.Company[c]) {
                                    MonthWiseData.push([parseInt(temp.Data[i].Amount)]);
                                    var flag = 1;
                                }
                            }
                            if (flag == 0) {
                                MonthWiseData.push([parseInt(0)]);
                            }
                        }
                        ChartData.push('[' + MonthWiseData + ']');
                    }
                    for (var m = 0; m < temp.Month.length; m++) {
                        temp.Month[m] = "{label:'" + temp.Month[m] + "'}";
                    }
                   
                   
                    var ticks = eval('"' + temp.Company + '"');
                    var legend = "[" + temp.Month + "]";
                    var ChartLabel = ticks.split(",");
                    var ChartLegend = eval(legend);
                    if (ChartData.length == 0) {
                        $("#DelayedMilestones").empty();
                        $("#DelayedMilestones").append('<h2 style="margin:130px 0 0 40px;">No Milestones Delay</h2>');                      
                    }
                    DelayedMilestones = $.jqplot('DelayedMilestones', eval('[' + ChartData + ']'), {
                        // stackSeries: true,
                        title: 'Delayed Milestones ' + Title,//(Period Jan-Mar 2014)',
                        captureRightClick: true,
                        seriesDefaults: {
                            renderer: $.jqplot.BarRenderer,
                            rendererOptions: {
                                barMargin: 30,
                                highlightMouseDown: true
                            },
                            rendererOptions: { fillToZero: false },
                            pointLabels: { show: true }
                        },
                        series: ChartLegend,
                        axes: {
                            xaxis: {
                                renderer: $.jqplot.CategoryAxisRenderer,
                                ticks: ChartLabel,
                                labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
                                tickRenderer: $.jqplot.CanvasAxisTickRenderer
                            },
                            yaxis: {
                                padMin: 0
                            }
                        },
                        legend: {
                            show: true,
                            location: 'ne',
                            placement: 'outsideGrid'
                        },
                        grid: { drawBorder: false }
                    }).replot();
                }
            });
        }
        catch (e) {
        }
    }   
</script>


Now Add the div in your webpage body to render the chart.

<div id="dvDelayedMilestones" class="HalfSpace"><div id="DelayedMilestones"></div></div>


Create an action to make an AJAX call for chart data like following.

[HttpGet]
        public JsonResult DelayedMilestoneChartData(string Criteria, string FromYear, string FromMonth, string ToYear, string ToMonth, string ProjectList)
        {
            DashBoardServices Dashboard = new DashBoardServices();
            DataSet dsCustomers = new DataSet();
            dsCustomers = Dashboard.GetDelayedMilestoneChart(Criteria, FromYear, FromMonth, ToYear, ToMonth, ProjectList);
            var data = DataTableExtensoins.ToList<DashboardGridModel>(dsCustomers.Tables[0]).ToList();
            var months = data.Select(m => m.Month).Distinct().ToList();
            var company = data.Select(c => c.CustomerName).Distinct().ToList();
            return Json(new { Data = data,Month = months, Company = company }, JsonRequestBehavior.AllowGet);
        }

Thursday, 20 March 2014

Add or Delete Feature Details Dynamically using JQuery

Add the following script

function AddFeatureRow() {
        var row = jQuery('#feature tbody>tr:last').clone(true);
        //Retrive text box and rename its id and clear value
        var index = parseInt(jQuery("td span", row).text()) + 1;
        //jQuery("td input:text", row).val("");
        //jQuery("td input:text", row).attr('id', 'fet_' + index);
        jQuery("td [id^=txtDescription]", row).val("");
        jQuery("td [id^=txtDescription]", row).attr('id', 'txtDescription_' + index);
        jQuery("td [id^=txtDescription]", row).attr('name', 'Description_' + index);
        jQuery("td [id^=txtQuantity]", row).val("");
        jQuery("td [id^=txtQuantity]", row).attr('id', 'txtQuantity_' + index);
        jQuery("td [id^=txtQuantity]", row).attr('class', 'Quantity');
        jQuery("td [id^=txtPrice]", row).val("");
        jQuery("td [id^=txtPrice]", row).attr('id', 'txtPrice_' + index);
        jQuery("td [id^=txtPrice]", row).attr('class', 'Price');
        jQuery("td [id^=txtTotal]", row).val("");
        jQuery("td [id^=txtTotal]", row).attr('id', 'txtTotal_' + index);
        jQuery("td textarea", row).val("");
        jQuery("td textarea", row).attr('id', 'txtDescription_' + index);
        jQuery("td span", row).attr('id', 'SrNo_' + index);
        //Retrive href link and rename its attribute
        jQuery("td a", row).attr('id', 'lnk_' + index);
        jQuery(row).attr('featureid', '0');
        //row.insertBefore('#feature tbody>tr:first');
        row.insertAfter('#feature tbody>tr:last');
        jQuery(row).show();
        UpdateFeatureSequence();

    }
    //Remove Feature when user click on delete button
    function FeatureRemoveRow(obj) {
        jConfirm('Are you sure you want to delete ?', 'Delete', function (r) {
            if (r == true) {
                var RowObj = jQuery(obj).parent().parent();
                var Featureid = parseInt(jQuery(RowObj).attr('featureid'));
                var Productid = jQuery("td input:text", RowObj).attr('productid');
                //if Feature is already saved then we need to remove from db for that we are hide this row
                if (Featureid > 0 && Productid > 0) {
                    jQuery(obj).parent().parent().hide();
                }
                else {
                    jQuery(obj).parent().parent().remove();
                }
                UpdateFeatureSequence();
                calculateSum();
            }
          
        });
    }
    function UpdateFeatureSequence() {
        var count = 0;
        jQuery('#feature > tbody  tr:visible').find('.SrNo').each(function (i, e) {
            jQuery(e).text(i + 1);
            count++;
        });
        //jQuery('#feature > tbody  tr:visible').find('td textarea').each(function (i, e) {
        //    jQuery(e).attr('id', 'txtDescription_' + (i + 1));
        //});
        jQuery('#feature > tbody  tr:visible').find('[id^=txtPrice]').each(function (i, e) {
            jQuery(e).attr('id', 'txtPrice_' + (i + 1));
        });
        jQuery('#feature > tbody  tr:visible').find('[id^=txtTotal]').each(function (i, e) {
            jQuery(e).attr('id', 'txtTotal_' + (i + 1));
        });
        jQuery('#feature > tbody  tr:visible').find('[id^=txtQuantity]').each(function (i, e) {
            jQuery(e).attr('id', 'txtQuantity_' + (i + 1));
        });
        jQuery('#feature > tbody  tr:visible').find('[id^=lnk]').each(function (i, e) {
            jQuery(e).attr('id', 'lnkDelete_' + (i + 1));
            jQuery(e).attr('class', 'icon-delete');
            jQuery(e).attr('onclick', 'FeatureRemoveRow(this)');
            jQuery(e).attr('title', 'Delete');
        });
        jQuery('#feature > tbody  tr:last').find('[id^=lnk]').each(function (i, e) {
            jQuery(e).attr('id', 'lnkAdd_' + count);
            jQuery(e).attr('class', 'icon-add');
            jQuery(e).attr('onclick', 'AddFeatureRow()');
            jQuery(e).attr('title', 'Add');
        });
    }

 function SaveInvoice() {
 var InvoiceDetail = new Array();
        var srno = 1;
        $('table > tbody  tr:visible').each(function (i, e) {
            var Description = jQuery(e).find('input[id *= Description]').val();
            var Amount = jQuery(e).find('input[id *= Total]').val();
            var qty = jQuery(e).find('input[id *= Quantity]').val();
            var rate = jQuery(e).find('input[id *= Price]').val();
            var DF_MileStoneId = null;
            if ($("input[type='radio'][name='InvoiceType']:checked").val() != LS) {
                DF_MileStoneId = jQuery(e).find('select[id *= Milestone] option:selected').val()
            }
            if (Description != '' || (Amount != '')) {
                var invoiceDetail = {
                    Description: Description,
                    Amount: Amount,
                    SrNo: srno,
                    Qty: qty,
                    Qty_Unit: $('#optMaxQtyUnit option:selected').val(),
                    Rate: rate,
                    DF_MileStoneId: DF_MileStoneId
                };
                InvoiceDetail.push(invoiceDetail);
            }
            srno = srno + 1;
        });
  //Now pass the InvoiceDetail in AJAX CALL
  }

Now Create a table in which the operation will performed.

<div>              
 <table   class="table table-bordered table-striped table-hover" id="feature" cellpadding="5px" width="20%">
  <thead>
   <tr>
    <th width="7%" class="text-center">
     <label id="lblSr">Sr</label>
     <input type="hidden" value="" id="hdfTotalinvoiceAmount" />
     <input type="hidden" value="" id="hdfTotalProjectAmount" />
    </th>
    <th>
     <label id="Label1">Description</label>
    </th>
    <th>
     <label id="Label1">Milestone</label>
   
    </th>
    <th>
     <label id="Label2">Qty (Units)</label>
     <input type="hidden" value="" id="hdfMaxQty" />
    </th>
    <th>
     <label id="Label3">Rate</label>
    </th>
    <th>
     <label id="Label4">Amount</label>
    </th>
    <th width="5%">&nbsp;
    </th>
   </tr>
  </thead>
  <tbody>
   
   <tr featureid="0" style="vertical-align: top;">
    <td class="text-center">
     <span id="SrNo_1" class="SrNo">1</span>
    </td>
    <td>
     @*<textarea rows="2" cols="75" id="txtdescription_1" placeholder="e.g. project go live (10 %)"></textarea>*@
     <input type="text" name="Description" id="txtDescription_1" placeholder="e.g. Project Go Live (10 %)" style="width: 435px;" />
    </td>
    <td>
     <select  id="optMilestone" style="width: 120px;" class="milestone"   onchange="FillMilestoneAmount($(this).val(),$(this).closest('tr').prevAll('tr').length + 1)">
      <option value="0"  itemid="" >Select</option>
    
     </select>
    </td>
  
    <td>
     <input type="text" id="txtQuantity_1" class="Quantity" style="width: 85px; text-align: right;" placeholder="e.g. 1" />
    </td>
    <td>
     <input type="text" id="txtPrice_1" onkeyup="CalculateAmount(this);" class="Price" style="width: 85px; text-align: right;" placeholder="e.g. 5000" />
    </td>
    <td>
     <input type="text" id="txtTotal_1" class="Amount" readonly="true" style="width: 95px; text-align: right;" />
    </td>
    <td width="5%">
     <a href="javascript:void(0)" id="lnkAdd" class="icon-add" onclick="AddFeatureRow();">
      @*<i class="icon-add"></i>*@
     </a>
    </td>
     @{
      index = index + 1; /*Resoution of control duplicate id when we are creating clone of the hidden row*/
   }
   </tr>
   <tr featureid="0" style="display: none; vertical-align: top;">
    <td class="text-center">
     <span id="SrNo0_1" class="SrNo">1</span>
    </td>
    <td>
     @*<textarea rows="2" cols="75" id="txtDescription0_1" placeholder="e.g. Project Go Live (10 %)"></textarea>*@
     <input type="text"  name="Description" id="txtDescription0_1" placeholder="e.g. Project Go Live (10 %)" style="width: 435px;" />
    </td>
     <td>
     <select  id="sel0_1" style="width: 120px;" class="milestone"   onchange="FillMilestoneAmount($(this).val(),$(this).closest('tr').prevAll('tr').length + 1)">
      <option value="0"  itemid="" >Select</option>
     </select>
    </td>
    <td>
     <input type="text" id="txtQuantity0_1" class="Quantity" style="width: 85px; text-align: right;" placeholder="e.g. 1" />
    </td>
    <td>
     <input type="text" id="txtPrice0_1" onkeyup="CalculateAmount(this);" class="Price" style="width: 85px; text-align: right;" placeholder="e.g. 5000" />
    </td>
    <td>
     <input type="text" id="txtTotal0_1" class="Amount" readonly="true" style="width: 95px; text-align: right;" />
    </td>
    <td width="5%">
     <a href="javascript:void(0)" title="Delete" onclick="FeatureRemoveRow(this)" id="lnkDelete0_1" class="btnDelete">
      @* <i class="icon-remove"></i>*@
     </a>
    </td>
     @{
      index = index + 1; /*Resoution of control duplicate id when we are creating clone of the hidden row*/
   }
   </tr>
  </tbody>
 </table>
</div>
 

Monday, 9 December 2013

Change TabIndex on Hide/Show Elements - JQuery

Hello Friends,

This scenario comes sometimes. when we need conditional tabbing with selecting some option will hide some elements or show some elements so in that case we need to change TabIndex dynamically like the following image.
When I select Cat2 in Dropdownlist all textboxes are visiable.


Now when I select Cat3 Textbox 4,6 and 9 are invisiable and Textbox7 comes in place of Textbox4. so after Textbox3 Cursor should move to Textbox7 and then Textbox5. so I need to change Tabindex of Textbox7 to 4.

for that I am using JQuery's nextuntil() function. so I can replace the following elements of Hidden Element to new TabIndex into the same div.

<script type="text/javascript">
    function changeDrp()
    {
        var value = $("#Select").val();
        if (value == "Cat1")
        {
            ResetAll();
            $("#Test8").hide();
            $("#Test5").hide();
            $("#Test6").hide();
            $("#Test1").hide();
            NewAssignTab();
        }
        else if (value == "Cat2")
        {          
            $("*[ dataitem ='Textbox']").show();
            ResetAll();
        }
        else if (value == "Cat3")
        {
            ResetAll();
            $("#Test6").hide();
            $("#Test9").hide();
            $("#Test4").hide();
            NewAssignTab();
        }
    }

    function NewAssignTab()
    {      
        jQuery("*[ dataitem ='Textbox']").each(function ()
        {        
            if (this.style.display == "none")
            {
                var pre,next;
                next = this.tabIndex;
                $("#" + this.id).nextUntil("#class:last").each(function ()
                {
                    pre = this.tabIndex;
                    this.tabIndex = next;
                    next = pre;                  
                });
            }
        });
    }

    function ResetAll()
    {
        jQuery("*[ dataitem ='Textbox']").each(function ()
        {          
            this.tabIndex = $("#" + this.id).attr("originaltab");
        });
    }
</script>

<div id="main">
     @{
        List<SelectListItem> listItems = new List<SelectListItem>();
        listItems.Add(new SelectListItem
        {
            Text = "Cat1",
            Value = "Cat1"
        });
        listItems.Add(new SelectListItem
        {
            Text = "Cat2",
            Value = "Cat2",
            Selected = true
        });
        listItems.Add(new SelectListItem
        {
            Text = "Cat3",
            Value = "Cat3"
        });
    }

    @Html.DropDownList("Select", listItems, new { onchange="changeDrp();" })<br />

    <div id="dv1" style="width: 33%; float: left;">
        <input id="Test1" type="Text" value="1" tabindex="1" dataitem ="Textbox" originaltab ="1" />
        <input id="Test4" type="Text" value="4" tabindex="4" dataitem ="Textbox" originaltab ="4" />
        <input id="Test7" type="Text" value="7" tabindex="7" dataitem ="Textbox" originaltab ="7" class="last" />
    </div>
    <div id="dv2" style="width: 33%; float: left;">
        <input id="Test2" type="Text" value="2" tabindex="2" dataitem ="Textbox" originaltab ="2" />
        <input id="Test5" type="Text" value="5" tabindex="5" dataitem ="Textbox" originaltab ="5" />
        <input id="Test8" type="Text" value="8" tabindex="8" dataitem ="Textbox" originaltab ="8" class="last" />
    </div>
    <div id="dv3" style="width: 33%; float: left;">
        <input id="Test3" type="Text" value="3" tabindex="3" dataitem ="Textbox" originaltab ="3" />
        <input id="Test6" type="Text" value="6" tabindex="6" dataitem ="Textbox" originaltab ="6" />
        <input id="Test9" type="Text" value="9" tabindex="9" dataitem ="Textbox" originaltab ="9" class="last" />
    </div>
</div>

Here in Last Element of the Div I had added class="last" attribute. so JQuery function will stop assigning new Index to the Elements.

Monday, 28 October 2013

Add Textboxes Dynamically and get the values

Hello Friends,
      Sometimes we need to add the textboxes dynamically and get the values from that.

first add the code at design side.

<ul>
     <li class="websiteadd">
                        <label for="user_category">
                            Websites<sup>*</sup></label>
                        <div class="inputbox" style="width: 320px; height: 28px;">
                            <asp:TextBox ID="txtWebSite" MaxLength="50" Style="height: 28px; width:210px;" runat="server"
                                CssClass="input-text wid text txtWebSite addwebsite"></asp:TextBox>
                            <asp:Button CssClass="add-btn" ID="btnAddnewWebsite" OnClientClick="return fnAddCustomWebsite();"
                                runat="server" Text="+Add" />
                        </div>
                    </li>
                    <li class="websitedelete">
                        <asp:Panel ID="panelWebSite" CssClass="panelWebSite" runat="server" Style="margin-left: 131px;">
                        </asp:Panel>
                    </li>
                </ul>

Then add the script in the head part

<script type="text/javascript">
function fnAddCustomWebsite() {
            var web = $(".addwebsite").val();
            var re = /^(www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$/;
            if (!re.test(web)) {
                alert("Please Enter valid website name.");
                return false;
            }
            else {
                AddWeb++;
                var li_Web = $("<span></span>").append($("<div style='width: 320px; height:28px;'></div>").addClass("field-wrapper inputbox").append($("<input style='width: 220px; height:28px;' />").attr({ "id": "txtnewAddWeb" + AddWeb, "text": +web, "name": "txtnewAddWeb" + AddWeb }).val(web))
            .append($("<a></a>").attr({ "href": "javascript:void(0);", "class": "delete-amt", "style": "width:50px;" }).append("Delete").click(function () {
                $(this).parent().remove();
                return false;
            })));
                $(".panelWebSite").append($(li_Web));
                $(".addwebsite").val('');
                return false;
            }
        }
</script>


Then create the method to get the values as follows

public void AddWebSites()
        {
            try
            {
                UserWebsiteService objuserwebsiteservice = new UserWebsiteService();
               
                foreach (string key in Request.Params.AllKeys)
                {
                    if (key.Contains("txtnewAddWeb"))
                    {
                        string lblnewweb = Request.Params[key].ToString();
                        GEN_UserWebSite objNewWeb = new GEN_UserWebSite();
                        objNewWeb.CreatedBy = ProjectSession.UserID;
                        objNewWeb.CreatedDate = DateTime.Now;
                        objNewWeb.WebSiteName = lblnewweb.Trim();
                        objNewWeb.UserID = ProjectSession.UserID;
                        objuserwebsiteservice.InsertGEN_UserWebSite(objNewWeb);
                       
                    }
                }
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError(ex);
            }
        }


Now call this function on submit button.

Maintain Page Scrol after Postback on the page

Hello friends,

    Sometimes we need to maintain scroll position of the page after postback due to dropdown change or button click in that case follow the code.

if Dropdown Control      : onChange="ab();"
if Button Control            : onClientClick ="ab();"


next take one hidden field to maintain scrol value.

<asp:HiddenField ID="TOS" runat="server" />


put the script in the head part.

<script type="text/javascript">
        function ab() {
            $("#<%= TOS.ClientID %>").val($(window).scrollTop());
        }
        function scrol() {
            setTimeout(function () { $(window).scrollTop($("#<%= TOS.ClientID %>").val()); }, 1);
        }
</script>


finally register the scrol function in last line of the event in code behind page.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "JavaScript:scrol();", true); 

Friday, 25 October 2013

Form Validation Using jQuery and Regular Expressions

Form Validation Using jQuery and Regular Expressions

Regular expressions offer an extremely flexible and powerful way of adding validation to your website forms. Combined with jQuery, it allows you to ensure that data sent to the server matches all of your requirements.

In this post I have included several example regular expressions that we have used in our web design projects for validating form input.

For this tutorial we assume you know how to create the HTML form and add jQuery to your site. For samples you can refer to previous posts – check passwords using jQuery, email validation using jQuery or view the demo form.

1 – Validates Numeric Characters Only
Accepts only 0 – 9
$('#TxtUpdateTime').keyup(function () {
            var val = $(this).val();
            var orignalValue = val;
            val = val.replace(/[0-9]*/g, "");
            if (val != '') {
                orignalValue = orignalValue.replace(/([^0-9].*)/g, "")
                $(this).val(orignalValue);             
            }
        });


2 - No Special Characters
Allows only letters, numbers and spaces. All other characters will return an error.

$('.keyup-characters').keyup(function() {
    $('span.error-keyup-2').remove();
    var inputVal = $(this).val();
    var characterReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-2">No special characters allowed.</span>');
    }
});

3 – Maximum Of 8 Characters
Allows all characters up to a maximum of 8. Useful for passwords, etc. The value can easily be increased/descreased by changing the {0,8}

$('.keyup-limit-8').keyup(function() {
    $('span.error-keyup-3').remove();
    var inputVal = $(this).val();
    var characterReg = /^([a-zA-Z0-9]{0,8})$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-3">Maximum 8 characters.</span>');
    }
});

4 - Check Email Address Format
This is a standard regular expression, which is used to validate email addresses to ensure they follow the standard format:

$('.keyup-email').keyup(function() {
    $('span.error-keyup-7').remove();
    var inputVal = $(this).val();
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if(!emailReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-7">Invalid Email Format.</span>');
    }
});

4 - Regex for float numbers

/^[-+]?[0-9]*\.?[0-9]+$/

Wednesday, 25 September 2013

Fix the Filter on top while scrolling the page


Hello All,
Some times we need to fix the filter on the top of the screen at the time we scroll the page. for that simply we need to change the css of that div in which we placed the filter. I have also fixed the header of the gridview.
For this code as follow

<script type="text/javascript">
        jQuery(function ($) {
           
            $(window).scroll(fixDiv);
            fixDiv();
        });
        function fixDiv() {
            var $cache = $('#getFixed');
            var $grid = $('#gvImage .FrozenHeader');
            if ($(window).scrollTop() > 80) {
                $cache.css({ 'position': 'fixed', 'top': '0px', 'padding-top': '10px', 'width': '1122px', 'margin': '0px 0px 0px 0px', 'border-bottom': '20px solid gray', 'border-top': '10px solid gray' });
                $grid.css({ 'position': 'fixed', 'top': '60px', 'left': '8px', 'width': '620px', 'padding-top': '0px', 'margin-top': '0px' });
            }
            else {
                $cache.css({ 'position': 'relative', 'width': '100%', 'top': '10px', 'padding-top': '10px' });
                $grid.css({ 'position': 'relative' });
            }
        }
</script>


and code for my filter and gridview is

<div id="getFixed" style="background-color: Yellow; height: 30px; top: 10px;">
            Filter :        
            <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:Button id="btnSearch" runat="server" Text="Search" />
</div>


<asp:GridView ID="gvImage" runat="server" AutoGenerateColumns="false" ClientIDMode="Static" BackColor="White">
                            <HeaderStyle CssClass="FrozenHeader" />
                            <Columns>
                                <asp:TemplateField HeaderText="Sr No." HeaderStyle-HorizontalAlign="Center">                                   
                                    <HeaderStyle Width="100" />
                                    <ItemStyle HorizontalAlign="Center" Width="100" />
                                    <ItemTemplate>
                                        <asp:Label ID="lblID" CssClass="lblID" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <Columns>
</asp:GridView>
 

Tuesday, 18 June 2013

Check for Duplicate Email ID using JQuery

Sometimes we need to check for duplicate EmailID or Username on Keypress. So this code will help you to check for duplicate and valid EmailID in your database.

First create teh textbox to enter the Email ID.

<asp:TextBox ID="txtEmail" runat="server" CssClass="input-text email duplicate-email txtemail"    MaxLength="100"></asp:TextBox>

Now add the following code to your header part.

<script type="text/javascript">

$(document).ready(function () {
     $('.duplicate-email').live('keypress blur', function (e) {
                if (e.keyCode === 9) {
                    emailvalidation();
                }
      });
});

 function emailvalidation() {
            SetLoader();
            var txtemail = $(".txtemail").val();
            var regemail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
            if (!regemail.test(txtemail)) {
                $('.lblmsg').text('Enter valid e-mail.');
                $(".msg_div").show();
                HideLoading();
            }
            else
                checkDupEmail(txtemail);
        }

function checkDupEmail(emailid) {
            SetLoader();
            $.ajax({
                type: "POST",
                url: "Registration.aspx/DuplicateEmailID",
                data: JSON.stringify({ EmailID: emailid }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                error: function (data) {
                    jAlert("er=" + data.d, siteTitle, '');
                    return false;
                },
                success: function (data) {
                    var status = data.d;
                    if (status == true) {
                        $('.lblmsg').text('Email Already exist.');
                        $(".msg_div").show();
                        HideLoading();
                        return false;
                    }
                    else {
                        $(".msg_div").hide();
                        HideLoading();
                        return true; ;
                    }
                }
            });
        }

</script>

Now add the webmethod tobe called by AJAX. Here DubplicateEmailID is a WebMethod. I used LINQ method I written the query in CheckDuplicateByEmailID method which will return true or false.

 [WebMethod]
        public static bool DuplicateEmailID(string EmailID)
        {
            try
            {
                UserInfoService objUserInfoService = new UserInfoService();
                bool IsExist = objUserInfoService.CheckDuplicateByEmailID(EmailID.Trim());
                return IsExist;
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError(ex);
                return false;
            }
        }

Friday, 17 May 2013

Change color statuswise in GridView using JQuery

Sometimes we need to change color into Gridview statuswise. we can use RowDataBound event to do this but this can be easily done using JQuery.

Here is the code to do so...

<script language="javascript" type="text/javascript">
$(document).ready(function () {
            $('.Users).find("td:nth-child(5)").each(function () {
                if ($(this).children("span").html() == Active) {
                    $(this).css("color", "Green");
                    $(this).css("border-color", "Black");
                }
                else if ($(this).children("span").html() == InActive) {
                    $(this).css("color", "Red");
                    $(this).css("border-color", "Black");
                }
            });
        });
    </script>

Here in $('.Users') is a CssClass name of Gridview.

Give the CssClass attribute to your Gridview control like this. And use TemplateField and use Label element for that column.

<asp:GridView ID="gvUserList" runat="server" CssClass="Users"></asp:GridView>

If you are using BoundField in a Gridview control then you can try the following.

<script language="javascript" type="text/javascript">
$(document).ready(function () {
            $('.Users).find("td:nth-child(5)").each(function () {
                if ($(this).text() == Active) {
                    $(this).css("color", "Green");
                    $(this).css("border-color", "Black");
                }
                else if ($(this).text() == InActive) {
                    $(this).css("color", "Red");
                    $(this).css("border-color", "Black");
                }
            });
        });
    </script>

Note : Here nth-child(5) is column number and it starts from 1 not 0.

Saturday, 6 April 2013

From Date - To Date with JQuery

In this post I will explain to have Jquery Date Picker for FromDate & ToDate with MinDate, MaxDate Validation.

Add two Textbox in your page.

                From Date :
                <asp:TextBox ID="txtFDate" runat="server" ClientIDMode="Static"></asp:TextBox>
         
                To Date :
                <asp:TextBox ID="txtTDate" runat="server" ClientIDMode="Static"></asp:TextBox>
         
then add the following script in your head part.

<script src="../Scripts/jquery.ui.datepicker.js" type="text/javascript"></script>
    <link href="../Styles/jquery-1.9.1.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">

        $(document).ready(function () {
            DatePick();
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(DatePick);
        });


        function DatePick() {
            $("#txtFDate").datepicker({
                buttonImage: '',
                buttonImageOnly: true,
                changeMonth: true,
                format: 'dd/MM/yyyy',
                changeYear: true,
                showOn: 'both',
                onSelect: function (selectedDate) {
                    $("#txtTDate").datepicker("option", "minDate", selectedDate);
                }
            });

            $("#txtTDate").datepicker({
                buttonImage: '',
                buttonImageOnly: true,
                changeMonth: true,
                format: 'dd/MM/yyyy',
                changeYear: true,
                showOn: 'both',
                onSelect: function (selectedDate) {
                    $("#txtFDate").datepicker("option", "maxDate", selectedDate);
                }
            });
        }      
    </script>