ASP.Net onclick not firing when checkbox is checked - asp.net

I'm building an asp.net/C# application that has several true/false questions, along with some multiple choice questions, in it. I've written code for this, and for some reason the onclick() event is not triggering when a checkbox is clicked. This is confirmed working in another app ; I don't understand why it isn't working here. Please see the relevant code below. I've sat this code side-by-side with the known working code, and can't find any anomalies. Does anyone have an idea why this isn't working?
<script type="text/javascript">
function ChkQuestion1(obj) {
var chk1a = document.getElementById("<%=chkFalse1.ClientID %>");
var chk1b = document.getElementById("<%=chkTrue1.ClientID %>");
if (obj.checked == true) {
chk1a.checked = false;
chk1b.checked = false;
obj.checked = true;
}
}
function ClientValidation1(source, arguments) {
var chka = document.getElementById("<%=chkFalse1.ClientID%>");
var chkb = document.getElementById("<%=chkTrue1.ClientID%>");
if (chka.checked == false && chkb.checked == false) {
arguments.IsValid = false;
}
}
</script>
<tr>
<td valign="top">1.</td>
<td width="70px" valign="top">
<asp:CheckBox ID="chkTrue1" runat="server" Text=" " onclick="ChkQuestion1(this)" />
<asp:Label ID="lblTrue1" runat="server" Text="True"></asp:Label></td>
<td width="90px" valign="top">
<asp:CheckBox ID="chkFalse1" runat="server" Text=" " onclick="ChkQuestion1(this)" />
<asp:Label ID="lblFalse1" runat="server" Text="False"></asp:Label>
</td>
<td>
<asp:Label ID="lblP1" runat="server" Text="This is a test True/False Question."></asp:Label>
<asp:CustomValidator ID="cvTwo" runat="server" ErrorMessage="Please select correct answer true/false." ToolTip="Please select correct answer true/false." ForeColor="Red" ValidationGroup="Employee" ClientValidationFunction="ClientValidation1">*</asp:CustomValidator>
</td>
</tr>

Related

How to make the TextBox border become red when a validation happens to it in asp.net?

This what i want to do.click to view photo
I tired many options but all did not work. like overriding JS methods and custom methods. i will be thankful for a clear, working response.
<tr>
<td class="auto-style2"> <asp:Label ID="Label2" runat="server" Text="Name"
CssClass="style3" AssociatedControlID="TextBoxName"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"
CssClass="TextBox"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3"
runat="server" ErrorMessage="Field required"
ControlToValidate="TextBoxName" Text="Required"
ForeColor="Red" Font-
Strikeout="False" Font-Underline="False" Font-
Overline="False" Font-Bold="True" BackColor="Red">
</asp:RequiredFieldValidator>
</td>
<td> </td>
</tr>
This is a script I use for this purpose.
<script type="text/javascript">
//set the interval for checking the validators
setInterval(function () { colorBorders() }, 100);
function colorBorders() {
if (typeof (Page_Validators) !== 'undefined') {
//loop all the validators
for (var i = 0; i < Page_Validators.length; i++) {
var validator = Page_Validators[i];
var control = document.getElementById(validator.controltovalidate);
//check if the control actually exists
if (control != null) {
//if the validator is not valid color the border red, if it is valid return to default color
//elseif with rgb color is nessecary for preventing chrome dropdown blinking
if (!validator.isvalid) {
control.style.borderColor = '#ff0000';
} else if (control.style.borderColor == "rgb(255, 0, 0)") {
control.style.borderColor = '#000000';
}
}
}
}
}
</script>

Hide EmptyDataTemplate but leave header visible

I have an EmptyDataTemplate on my ASP.NET webform which allows users to add a record to the database. Depending on the permissions of the user, this EmptyDataTemplate needs to be visible and hidden if no data is found (I have this working!)
For example, my user has Read Access only. When they search a specific criteria, no results are displayed they cannot see the EmptyDataTemplate. However, if they search a criteria, and there is data, data is displayed WITHOUT the headers.
Can someone please help explain why this is happening and if there's a way around it?
The headers are HeaderText on TemplateFields.
I'm hoping it's a general trick.
Thank you in advance for your help!
Please note, it's the HeaderText in the TemplateFields I want to display- not the in the emptyDataTemplate as they'll head up the columns of data that match the search criteria.
edit: code added as requested
For hiding the EmptyDataTemplate:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Control control = null;
control = GridView1.Controls[0].Controls[0];
if (userManagement.getMIFReadWriteAccess() == "Read")
{
control.Visible = false;
Export_All.Visible = true;
}
else if (userManagement.getMIFReadWriteAccess() == "Write")
{
control.Visible = true;
Export_All.Visible = true;
}
}
in markup for the header text (i've only shown one column but the markup is the same for all of them)
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_Index" runat="server" Text='<%#Eval("id") %>'></asp:Label>
<asp:Label ID="lbl_ID" runat="server" Text="" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
EmptyDataTemplate:
<EmptyDataTemplate>
<div id="emptyData" runat="server">
<tr>
<th></th>
<th>Serial Number</th>
<th>Comments</th>
<th>Review Date</th>
<th>Approved By</th>
</tr>
<tr>
<td>
<asp:Button runat="server" ID="btInsert" Text="In" OnClick="Add" CommandName="EmptyDataTemplate" Class="Button" OnClientClick="return confirm('You are about to confirm this action. Please confirm this action by clicking OK. If you do not wish to do this, please select Cancel.');" />
<br />
<asp:Button runat="server" ID="btInsertOut" Text="Out" OnClick="AddOut" CommandName="EmptyDataTemplate" Class="Button" OnClientClick="return confirm('You are about to confirm this action. Please confirm this action by clicking OK. If you do not wish to do this, please select Cancel.');" />
</td>
<td>
<asp:TextBox runat="server" ID="tb_Serial_Number" CssClass="text"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="tb_comments" Width="100%" MaxLength="50" runat="server" placeholder="max 50 characters"/>
</td>
<td>
<asp:TextBox ID="tb_reviewDate" runat="server" DataFormatString="{0:dd/mm/yyyy}" Text='<%#Eval("review_by") %>'></asp:TextBox>
</td>
<td><asp:DropDownList ID="tb_approved_by" runat="server">
</asp:DropDownList> </td>
</tr>
</div>
</EmptyDataTemplate>
After trial and error, I found that programatically adding a header row in C# did the trick. Probably not the best way of doing it, but it worked.
Code is as follows:
#region show the emptyDataTemplate depending on user rights
Control control = null;
control = GridView1.Controls[0].Controls[0];
if (userManagement.getMIFReadWriteAccess() == "Read")
{
control.Visible = false;
GridViewRow HeaderRow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell2 = new TableCell();
HeaderCell2.Text = "Country";
HeaderCell2.ColumnSpan = 1;
HeaderRow.Cells.Add(HeaderCell2);
//Repeat the above for every column of data you have!
GridView1.Controls[0].Controls.AddAt(0, HeaderRow);

Client Validation Function for Radio Buttons on a ASPX file

This is an ASPX/CS program with Javascript.
I have inherited this code and I am trying to complete the validation which was not completed. I have found the javascript code which validates of a radio button is clicked but the aspx code does not reference it.
Radio buttons are grouped together such that when one in the group is selected, the others are unselected. But, for starters, I cannot see how to utilize this. It must have something to do with the "GroupName" that each radio button mentions.
<ItemTemplate>
<%# FormatGroup(Eval("Group").ToString()) %>
<tr>
<td> <asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("Question") %>'><%# Eval("Question") %></asp:Label></td>
<td align="center" width="10%"><asp:RadioButton ID="rblEvalQuestion4" runat="server" GroupName='<%# Eval("Question") %>' /></td>
<td align="center" width="10%"><asp:RadioButton ID="rblEvalQuestion3" runat="server" GroupName='<%# Eval("Question") %>' /></td>
<td align="center" width="10%"><asp:RadioButton ID="rblEvalQuestion2" runat="server" GroupName='<%# Eval("Question") %>' /></td>
<td align="center" width="10%"><asp:RadioButton ID="rblEvalQuestion1" runat="server" GroupName='<%# Eval("Question") %>' /></td>
</tr>
</ItemTemplate>
So how would I make use of the ClientValidationFunction method in asp for radio button groups?
Try a custom field validator.
Add this bit of JavaScript:
<script language="javascript" type="text/javascript" >
function ClientValidate(source,args)
{
if(document.getElementById("<%= rblEvalQuestion1.ClientID %>").checked || document.getElementById("<%= rblEvalQuestion2.ClientID %>").checked || document.getElementById("<%= rblEvalQuestion3.ClientID %>").checked || document.getElementById("<%= rblEvalQuestion4.ClientID %>").checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
</script>
Add this validator to the page:
<asp:CustomValidator id="RadioButtonValidator" runat="server" Display="Dynamic" ErrorMessage="Please select an option." ClientValidationFunction="ClientValidate" OnServerValidate="ServerValidate"></asp:CustomValidator>
And this method in the code behind:
protected void ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = rblEvalQuestion1.Checked || rblEvalQuestion2.Checked || rblEvalQuestion3.Checked || rblEvalQuestion4.Checked;
}
Finally, make sure to check if
Page.IsValid
in your button for submitting the form.
Finally, if you can re-factor this into a RadioButtonList you can simply just use a RequiredFieldValidator which will make your life a lot easier to implement!

Checkbox server/client events

I have a checkbox in repeater control.
on changing it's bit value, it should prompt the alert message like do u wish to delete?
and if yes is selected, the onselectedchange server event should be fired.
Right now. on clicking the checkbox i am using onclick event to fire the prompt but it is not able to fire the server event.
here is my code
<script language="javascript" type="text/javascript">
function CheckedChange() {
if (confirm('Are you sure you want to delete?'))
return true;
else
return false;
}
</script>
<asp:Repeater ID="repQuestion" runat="server" onitemcommand="repQuestion_ItemCommand" onitemdatabound="repQuestion_ItemDataBound">
<ItemTemplate>
<table width="100%" cellspacing="0" cellpadding="0">
<tr>
<td>
<asp:CheckBox onclick="return CheckedChange();" ID="delete" runat="server" Checked='<%#DataBinder.Eval(Container.DataItem, "IsDeleted")%>' OnCheckedChanged="chkdelete_Click" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Work around this snippet.
The Repeater.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td><%# Eval("Index") %></td>
<td>
<asp:CheckBox ID="delete" runat="server"
AutoPostBack="true"
Checked='<%# Convert.ToBoolean(Eval("IsDeleted")) %>'
Enabled='<%# !Convert.ToBoolean(Eval("IsDeleted")) %>'
OnCheckedChanged="chkdelete_Click"
onclick="javascript:return CheckedChange(this)"/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
JavaScript
function CheckedChange(objCheckBox) {
if (confirm('Are you sure you want to delete?')) {
__doPostBack("'" + objCheckBox.id + "'", '');
return true;
}
else {
objCheckBox.checked = false;
return false;
}
}
Page_Load Event
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
//bind gridview here
DataTable dataTable = new DataTable
{
Columns = { "Index", { "IsDeleted", typeof(bool) } }
};
bool temp = true;
for (var i = 0; i < 6; i++)
{
dataTable.Rows.Add((i + 1).ToString(), temp);
temp = !temp;
}
Repeater1.DataSource = dataTable;
Repeater1.DataBind();
}
}
catch (Exception exception)
{
//Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
}
}
Well, I don't personally like exposing the __doPostBack but this seems to be the only way in this case.
On an unrelated side note, if you are showing deleted items, its better to show them disabled.
Try by passing the UniqueID (that is the name of the Checkbox).
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td><%# Eval("Index") %></td>
<td>
<asp:CheckBox ID="delete" runat="server"
AutoPostBack="true"
Checked='<%# Convert.ToBoolean(Eval("IsDeleted")) %>'
Enabled='<%# !Convert.ToBoolean(Eval("IsDeleted")) %>'
OnCheckedChanged="chkdelete_Click"
onclick="javascript:return CheckedChange(this)"/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
JavaScript
function CheckedChange(objCheckBox) {
if (confirm('Are you sure you want to delete?')) {
__doPostBack("'" + objCheckBox.name + "'", '');
return true;
}
else {
objCheckBox.checked = false;
return false;
}
}
Try this
function confirmUser(checkBox)
{
if(checkBox.childNodes[0].checked === false){
alert('Your alert message');
}
}
<asp:Repeater ID="rptSelecteduserRoles" runat="server" OnItemDataBound="rptSelecteduserRoles_OnItemDataBound">
<ItemTemplate>
<asp:CheckBox ID="chkBox" CssClass="fieldLabel" AutoPostBack="False" onchange="confirmUser(this)"runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:Repeater>

asp:DropDownList

The following code works except the dropdown list is not returned to its original value when the validation fails any ideas?
<tr><td valign="top" style="padding-right: 10px;">
<b>Select Account:</b>
<asp:DropDownList ID="m_lstAccounts" runat="server" CausesValidation="true" ValidationGroup="Group1"
CssClass="dropdownList" OnSelectedIndexChanged="OnAccountChange" AutoPostBack="True"></asp:DropDownList>
<br />
<script type="text/javascript">
function ConfirmDropDownValueChange(source, arguments) {
if (document.all("AccountProfileDirty").value == "1") {
arguments.IsValid = confirm("Are you sure you want to continue with out saving?");
source.
}
else {
arguments.IsValid = true;
}
}
</script>
<asp:CustomValidator ID="ConfirmDropDownValidator" runat="server"
ClientValidationFunction="ConfirmDropDownValueChange" Display="Dynamic" ValidationGroup="Group1" /> </td> </tr>
What is the random source. in the middle of your ConfirmDropDownValueChange() function? That would certainly make JavaScript fail.

Resources