Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, 23 June 2015

Implement Mutually Exclusive CheckBoxList (CheckBoxes) inside GridView in ASP.Net

Mutually exclusive CheckBoxList means when one CheckBox is checked, all other CheckBoxes present in the CheckBoxList will be unchecked.

 HTML Markup
The following HTML Markup consists of a GridView with two BoundField columns and a TemplateField column containing an ASP.Net CheckBoxList control.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound = "OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
        <asp:TemplateField HeaderText="Gender" ItemStyle-Width="150">
            <ItemTemplate>
                <asp:CheckBoxList ID = "chkGender" runat="server" RepeatDirection = "Horizontal">
                    <asp:ListItem Text="Male" Value="M" />
                    <asp:ListItem Text="Female" Value="F" />
                </asp:CheckBoxList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>


protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Id"), new DataColumn("Gender"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "M", "Sujoy Santra", "India");
        dt.Rows.Add(2, "M", "Sumit Kumar Sen", "Brazil");
        dt.Rows.Add(3, "F", "Soumi Santra", "India");
        dt.Rows.Add(4, "M", "Mithun Patra", "Canada");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}







 Populating the Selected Value of CheckBoxList in GridView
Inside the OnRowDataBound event handler of GridView, first the value of Gender is determined from the DataItem object of the GridView.
Finally the CheckBoxList is referenced using the FindControl method and its selected value is set.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string gender = (e.Row.DataItem as DataRowView)["Gender"].ToString();
        CheckBoxList chkGender = (e.Row.FindControl("chkGender") as CheckBoxList);
        chkGender.Items.FindByValue(gender).Selected = true;
    }
}

 Implement Mutually Exclusive CheckBoxList (CheckBoxes) inside GridView
Inside the jQuery document ready event handler, a click event handler is assigned to each CheckBox of all the CheckBoxLists present inside the GridView.
When a CheckBox is clicked in a CheckBoxList, all the CheckBoxes except the current are unchecked.
<script type="text/javascript" src="script/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=chkGender] input").click(function () {
            $(this).closest("table").find("input").not(this).removeAttr("checked");
        });
    });
</script>

Thursday, 19 March 2015

ASP.Net RequiredFieldValidator not working when OnClientClick event is added to Button

Here  I will explain how to solve the problem of RequiredFieldValidator not working when OnCientClick event is added to the Button in ASP.NET.

In order to make the RequiredFieldValidator work with OnClientClick we need to make use of Page_ClientValidate JavaScript function of ASP.Net Validators to perform validation explicitly.

HTML Markup
The HTML markup consists of an ASP.Net TextBox, a RequiredFieldValidator and a Button which has an OnClientClick event handler attached.
Name:
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="Required" ControlToValidate="txtName"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" OnClientClick="return Validate();" />
<script type="text/javascript">
    function Validate() {
        return confirm('Do you want to submit data?');
    }
</script>


The Problem
The above code will display confirm and will not validate the TextBox using RequiredFieldValidator and the PostBack will happen even if the TextBox is left empty.

The Solution
Hence we need to make use of the Page_ClientValidate JavaScript function of ASP.Net Validators to perform validation explicitly as shown below.
Name:
<asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="Required" ControlToValidate="txtName"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" OnClientClick="return Validate();" />
<script type="text/javascript">
    function Validate() {
        if (Page_ClientValidate()) {
            return confirm('Do you want to submit data?');
        }
        return false;
    }
</script>

Here first the Page_ClientValidate JavaScript function will make sure that all Validators have validated the form and the validation is successful then only it will raise the JavaScript confirmation.

How to use with Validation Groups
When using Validation Groups you need to simply pass the name of the Validation Group to the Page_ClientValidate JavaScript function and it will only verify the validations of the validators belonging to that group.
<script type="text/javascript">
    function Validate() {
        if (Page_ClientValidate('ValidationGroupName')) {
            return confirm('Do you want to submit data?');
        }
        return false;
    }
</script>

Wednesday, 7 January 2015

Watermark in Textbox by javascript

 Watermark in Textbox by javascript:

Please write the script in aspx page:
 <script type="text/javascript">
        function WaterMarkFocus(txt, text) {
            if (txt.value == text) {
                txt.value = "";
                txt.style.color = "black";
            }
        }

        function WaterMarkBlur(txt, text) {
            if (txt.value == "") {
                txt.value = text;
                txt.style.color = "gray";
            }
        }
</script>

And write the code for Textbox:
<asp:TextBox ID="txtName" runat="server" Height="22px" Width="50px" Text="Name" onfocus="WaterMarkFocus(this,'Name')" onblur="WaterMarkBlur(this,'Name')"></asp:TextBox>


Friday, 10 October 2014

Digital Clock Using JavaScript

Digital Clock Using JavaScript:
Java Script:
-------------------
<script>
               function digclock() {
                   var d = new Date()
                   var t = d.toLocaleTimeString()

                   var hr = t.substring(0, 2)
                   var min = t.substring(3, 5)
                   var sec = t.substring(6, 8)

                   var time
                   if (hr >= 12) {
                       time = (hr - 12) + ':' + min + ':' + sec + ' ' + 'PM'
                   }
                   else {
                       time = hr + ':' + min + ':' + sec + ' ' + 'AM'
                   }

                   document.getElementById('<%= divTimer.ClientID%>').innerHTML = time
               }

               setInterval(function () { digclock() }, 1000)

</script>


HTML:
----------
<div id="divTimer" runat="server" style="font-size:small; color:white;" ></div>

Thursday, 29 May 2014

End Date must be greater than Start date in javascript

function compareDate()
{

var start = document.formName.begindate.value;
var end = document.formName.enddate.value;

var stDate = new Date(start);
var enDate = new Date(end);
var compDate = enDate - stDate;

if(compDate >= 0)
return true;
else
{
alert("Please Enter the correct date ");
return false;
}

Currency checking in javascript

<html>
<head>
<title> </title>
<script type="text/javascript">
    function validate() {
        var currency = document.getElementById("currency").value;
        var pattern = /^\d+(?:\.\d{0,2})$/ ;
        if (pattern.test(currency)) {
            alert("Currency is in valid format");
            return true;
        }
            alert("Currency is not in valid format!Enter in 00.00 format");
            return false;

    }
</script>
</head>
<body>
<h2>Validating Currency..</h2>
Enter Currency:<input type="text" name="currency" id="currency" />
<input type="submit" value="Check" onclick="validate();" />
</body>
</html>

Wednesday, 4 September 2013

Get value from popup page Javascript

sample1.html:
 
<html>
<head>
    <title>Sample 1</title>
</head>
<body>
<script language="JavaScript">
    function windowOpen() {
        var myWindow=window.open('sample2.html','windowRef','width=200,height=200');
       if (!myWindow.opener) myWindow.opener = self;
    }
</script>
<form name="frmMain" method="post" action="">
    <input type="text" value="" name="txtVol" id="txtVol">
    <input name="openPopup" type="button" id="openPopup" onClick="Javascript:windowOpen();" value="Get Value">
</form>
</body>
</html>
 
 
sample2.html:
 
<html>
<head>
   <title>Sample 2</title>
</head>
<body>
<script language="JavaScript">
    function updateOpener() {
        window.opener.document.frmMain.txtVol.value = document.frmMain.txtInput.value;
        window.close();
    }
</script>
Value :<form name="frmMain" method="post" action="">
    <input type="text" name="txtInput" value="">    
     <input name="Close" type="submit" id="Close"onClick="Javascript:updateOpener()" value="Close">
</form>
</body>
</html>