Step 1:- Javascript code
<script type="text/javascript">
function Validate()
{
var rblGender
= document.getElementById("rblGender");
var radio
= rblGender.getElementsByTagName("input");
var isChecked
= false;
for (var i
= 0; i < radio.length; i++) {
if (radio[i].checked)
{
isChecked
= true;
break;
}
}
if (!isChecked)
{
alert("Please
select a gender");
}
return isChecked;
}
</script>
Step 2:-
Server side code
var isChecked
= false;
foreach (ListItem list in rblGender.Items)
{
if (list.Selected)
{
isChecked
= true;
break;
}
}
if (!isChecked)
{
DisplayMessage("Please
select a gender");
return;
}
Step 3:-
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Validate()
{
var rblGender
= document.getElementById("rblGender");
var radio
= rblGender.getElementsByTagName("input");
var isChecked
= false;
for (var i
= 0; i < radio.length; i++) {
if (radio[i].checked)
{
isChecked
= true;
break;
}
}
if (!isChecked)
{
alert("Please
select a gender");
}
return isChecked;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Gender</td>
<td>
<asp:RadioButtonList ID="rblGender" runat="server" ClientIDMode="Static">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Step 4:-
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Demo
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
btnSubmit.Attributes.Add("onclick", "return
Validate();");
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var isChecked
= false;
foreach (ListItem list in rblGender.Items)
{
if (list.Selected)
{
isChecked
= true;
break;
}
}
if (!isChecked)
{
DisplayMessage("Please
select a gender");
return;
}
}
#region DisplayMessage
protected void DisplayMessage(string strMsg)
{
strMsg
= strMsg.Replace("\r\n", "\\n");
strMsg
= strMsg.Replace("\n", "\\n");
strMsg
= strMsg.Replace("'", "");
string scriptString
= @"<script
language=""JavaScript"">";
scriptString
+= "alert('" + strMsg + "');";
scriptString
+= "</script>";
ClientScript.RegisterStartupScript(this.GetType(), "Startup",
scriptString);
}
#endregion
}
}
No comments:
Post a Comment