I have created custom validation in aspx file for checkboxlist like
<asp:UpdatePanel ID="pnlUpdateAgency" runat="server">
....
....
<script type="text/javascript">
function validateCheckbox(sender, e) {
try {
e.IsValid = false;
var checkboxlist = document.getElementById('chklLineOfAuthority');
var inputlist = checkboxlist.getElementsByTagName('input');
for (var i = 0; i < inputlist.length; i++) {
if (inputlist[i].type == 'checkbox')
if (inputlist[i].checked) {
e.IsValid = true;
break;
}
}
}
catch (ex) {
alert(ex.Message);
}
}
</script>
...
...
<asp:CheckBoxList ID="chklLineOfAuthority" RepeatColumns="3" RepeatLayout="Table"
RepeatDirection="Horizontal" AutoPostBack="false" CausesValidation="false"
runat="server">
</asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Please select at least one option"
ClientValidationFunction="validateCheckbox"
ForeColor="Red" />
...
...
</asp:UpdatePanel>
Now the issue is custom validation not working in update panel.
Related
I have two address fields which has 46 textboxes and each one accepts only one character.
For eg.
Address
Line1 : 1.2.3.4....46
Line2 : 1.2.3.4...46
Now on checkbox oncheckchanged event,
I want to copy each character from textbox to another respectively and if checkbox is not checked then line one should be remained as it is.
How to accomplish this?
I tried googling but didn't help much.
<asp:TextBox runat="server" ID="line1_1" MaxLength="1" ></asp:TextBox><br/>
<asp:CheckBox runat="server" ID="if_same" Text="Same" OnCheckedChanged="if_same_CheckedChanged" AutoPostBack="true" />
<asp:TextBox runat="server" ID="line2_1" MaxLength="1" ></asp:TextBox><asp:TextBox runat="server" ID="line2_46" MaxLength="1" ></asp:TextBox>
protected void if_same_CheckedChanged(object sender, EventArgs e)
{
set_per_local();
}
public void set_per_local()
{
if (if_same.Checked == true)
{
checkIfNullEmpty();
disablelocal();
string line1_address = string.Concat(line1_1.Text,line1_46.Text);
try
{
for (int i = 0; i < line1_address.Length; i++)
{
line2_1.Text = line1_address[0].ToString();
line2_46.Text = line1_address[45].ToString();
}
}
catch (Exception)
{
throw;
}
}
else
{
Enablelocal();
}
}
public void checkIfNullEmpty()
{
if (string.IsNullOrEmpty(line1_1.Text)) line1_1.Text = " ";
if (string.IsNullOrEmpty(line1_46.Text)) line1_46.Text = " ";
}
public void disablelocal()
{
local_line1_address1.Enabled = false;
local_line1_address46.Enabled = false;
}
public void enablelocal()
{
local_line1_address1.Enabled = true;
local_line1_address46.Enabled = true;
}
I think this could be a better candidate for a client-side javascript or jQuery etc. Also, if you have followed a logical pattern for naming those 46 textboxes, in your javascript you could hook into the checkbox.changed event and start a loop walking each of the source fields and replace the target field textbox with the source value. Something like
<script>
$(".checkbox").change(function() {
if(this.checked) {
alltextboxes();
}
});
function copy alltextboxes()
{
for (int i = 0; i < 46; i++)
{
document.getElementById(tgtTbox+i).value = document.getElementById(srcTbox+i).value
}
}
</script>
Disclaimer: I have not tested this code though. I just typed it into the answer. based on your requirement, this code may need small modifications. Just note that this only works if your naming convention for the textbox labels follow a pattern (like "SourceText1, SourceText2, TargetText1, TargetText2 etc.").
I found this site more helpful.
http://www.dotnetspark.com/kb/3125-how-to-copy-textbox---text-to-another-one.aspx
<asp:TextBox runat="server" ID="TextBox1" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox2" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox3" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox4" MaxLength="1" size="1"></asp:TextBox>
<asp:CheckBox runat="server" ID="CheckBox1" Text="Same as above" onclick="CopyText()" />
<asp:TextBox runat="server" ID="iBox1" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox2" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox3" MaxLength="1" size="1"></asp:TextBox>
<asp:TextBox runat="server" ID="iBox4" MaxLength="1" size="1"></asp:TextBox>
<script type="text/javascript">
function CopyText() {
var cb = document.getElementById('CheckBox1');
var tb1 = document.getElementById('TextBox1');
var tb2 = document.getElementById('TextBox2');
var tb3 = document.getElementById('TextBox3');
var tb4 = document.getElementById('TextBox4');
var tb11 = document.getElementById('iBox1');
var tb12 = document.getElementById('iBox2');
var tb13 = document.getElementById('iBox3');
var tb14 = document.getElementById('iBox4');
if (cb.checked) {
tb11.value = tb1.value;
tb12.value = tb2.value;
tb13.value = tb3.value;
tb14.value = tb4.value; }
else {
tb11.value = '';
tb12.value = '';
tb13.value = '';
tb14.value = ''; }
}
}
<script>
I have a textbox, on click, it allows you to select date from calendar control. If the date is deleted, it should uncheck the checkbox available just next to the textbox.
With below code, I am able to achieve everything other than making the textbox readonly so that user is not able to type anything. Also, once the text is selected, checkbox gets checked but when text is deleted the checkbox doesn't get unchecked.
Can anyone suggest what needs I might be doing wrong here ?
<asp:CalendarExtender ID="CalForDate" runat="server" TargetControlID="txtDate" Format="MM/dd/yyyy" PopupPosition="BottomLeft" DefaultView="Days"></asp:CalendarExtender>
<asp:TextBox runat="server" ID="txtDate" AutoPostBack="true" EnableViewState = "false" onKeyPress="javascript:return ChkCheckBox()" OnTextChanged="txtDate_OnTextChanged"></asp:TextBox>
The javascript code:
function ChkCheckBox() {
var txtDate = document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_txtDate').value;
if (txtDate.length == 9) {
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = true;
}
else
{
document.getElementById('ctl00_ctl00_cphMSTMainPage_cphMSTLDAHomePage_chkDate').checked = false;
}
In pageload I have added:
if (!IsPostBack){
txtDate.Attributes.Add("readonly", "readonly");}
And on text changed:
public void txtDate_OnTextChanged(object o, EventArgs e){
if (!(string.IsNullOrEmpty(txtDate.Text)))
{
chkDate.Visible = true;
chkDate.Checked = true;
}
else
{
chkDate.Visible = true;
chkDate.Checked = false;
} }
You can easily achieve this using jquery. I am sending you the sample code. Please don't hesitate to ask further assistance if needed.
<script type="text/javascript">
$(document).ready(function () {
$('#txtDate').on('change', function () {
//console.log('Tested');
if ($(this).val().toString().trim() != '') {
$('[Id*=ckTest]').attr('checked', 'checked');
}
else {
$('[Id*=ckTest]').removeAttr('checked');
}
});
$('#btnClear').click(function () {
$('#txtDate').val('');
$('#txtDate').trigger('change');
});
});
</script>
The code file is as below.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true" ClientIDMode="Static"></asp:TextBox>
<asp:CheckBox ID="ckTest" runat="server" />
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" />
<button id="btnClear">Clear</button>
</div>
</form>
Just add jquery to project i used
jquery-2.1.4.min.js
I have problems in using CustomValidation control, I want to check if year entered in date of birth text field is less than graduation year selected from a drop down list by 20 years. I think using ClientValidationFunction is much better when i tried to use it:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="Enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" ClientValidationFunction="GraduationYearValidation"></asp:CustomValidator>
here is the script
<script type="text/javascript">
function GraduationYearValidation(sender, args) {
var brithYear = parseInt(new Date(document.getElementById('<%=txtBirthDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=ddlGraduationYear.ClientID%>').options[document.getElementById('<%=ddlGraduationYear.ClientID%>').selectedIndex].text);
if ((brithYear - gradeYear) < 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
I get those errors: document.getElementById(...) is null and GraduationYearValidation is not defined.
so, i tried to make it server side by:
<asp:CustomValidator ID="BirthYearCustomValidator" runat="server" ControlToValidate="ddlGraduationYear" ErrorMessage="enter a valid graduation year." SetFocusOnError="true" ValidationGroup="SaveEducationStep" Display="Dynamic" OnServerValidate="BirthYearCustomValidator_ServerValidate"></asp:CustomValidator>
code behind is :
protected void BirthYearCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
int brithYear = Convert.ToDateTime(txtBirthDate.Text).Year;
int gradeYear = Convert.ToInt32(ddlGraduationYear.SelectedValue);
if ((gradeYear - brithYear) < 20)
{
args.IsValid = false;
}
else
{
args.IsValid = true;
}
}
it doen't work and i searched for the reason i found it may be because i need to write Page.Validate("SaveEducationStep"); and check if Page.IsValid before save, but it still not working with me
any suggestion on both scenarios will be appreciated. thanks.
client side validation is working, check your code
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:DropDownList ID="dddate" runat="server">
<asp:ListItem Text="2014" Value="2014"></asp:ListItem>
<asp:ListItem Text="2013" Value="2013"></asp:ListItem>
<asp:ListItem Text="2012" Value="2012"></asp:ListItem>
<asp:ListItem Text="2011" Value="2011"></asp:ListItem>
</asp:DropDownList>
<asp:CustomValidator ID="CustomValidator1" ValidateEmptyText="true" EnableClientScript="true" runat="server" ErrorMessage="CustomValidator" ValidationGroup="test" ClientValidationFunction="abc" ControlToValidate="dddate"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" ValidationGroup="test" />
<script type="text/javascript">
function abc(sender, args) {
var birthYear = parseInt(new Date(document.getElementById('<%=txtDate.ClientID%>').value).getFullYear());
var gradeYear = parseInt(document.getElementById('<%=dddate.ClientID%>').options[document.getElementById('<%=dddate.ClientID%>').selectedIndex].text);
if ((gradeYear - birthYear) > 20) {
return args.IsValid = true;
}
else {
return args.IsValid = false;
}
}
</script>
I have a checkbox named Select All. When I click this then all other check box inside my Gridview is Checked. But I want when anyone of the checkbox inside the grid will be unchecked then this Select All Checkbox will automatically uncheck. Is there anyone who can help me on this Please?
Thank you.
function SelectheaderCheckboxes(headerchk) {
debugger
var gvcheck = document.getElementById('gvdetails');
var i;
//Condition to check header checkbox selected or not if that is true checked all checkboxes
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = true;
}
}
//if condition fails uncheck all checkboxes in gridview
else {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = false;
}
}
}
<asp:GridView ID="gvdetails" runat="server" DataSourceID="dsdetails" onrowdatabound="gvdetails_RowDataBound" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" onclick="javascript:SelectheaderCheckboxes(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchild" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can do this on the client or the server side
Client side using javascript/jquery
As the checkboxes are added dynamically you will need to use the on method to bind the checkboxes to the function and fire it when their state changes.
$(document).ready(function() {
$(".checkbox").on("change", function() {
if(!$(this).is(":checked")){
$(".selectAll").prop('checked', false);
}
});
});
Here is a jsFiddle with a full functioning select All that will:
Select All / Deselect All
Untick Select All when one of the checkboxes is unticked
Tick select All when all checkboxes are ticked
Server side
use an event handler to on a postback(ajax) when a checkbox is unticked and loop through all checkboxes and untick them
Font-end uses ajax to do a partial postback to update the gridview.
the select all checkbox and gridview checkboxes will trigger the postback.
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:GridView ID="gvCheckBoxes" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="cbCheckBox" OnCheckedChanged="CheckBoxChanged" AutoPostBack="true" runat="server" />
</ItemTemplate>
/asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cbSelectAll"/>
</Triggers>
</asp:UpdatePanel>
Code Behind
The select All check box event handler loops through the gridview and finds the checkboxes.
It ticks them if the select all checkbox is ticked otherwise it unticks them
The gridview checkbox event handler loops through the checkboxes and sets a flag to determine if it should tick or untick the select all checkbox. It exists the loop if any of the checkboxes are not ticked as select all must therefore be unticked as well
public void SelectAll (Object sender, Eventargs e)
{
foreach (var row in grid.Rows)
{
var checkBox = (CheckBox)row.FindControl("cbCheckBox");
checkBox.Checked = cbSelectAll.Checked;
}
}
public void CheckBoxChanged(Object sender, Eventargs e)
{
var isSelectAll = true;
foreach (var row in grid.Rows)
{
var checkBox = (CheckBox)row.FindControl("cbCheckBox");
if(!checkBox.Checked)
{
isSelectAll = false;
break;
}
}
cbSelectAll.Checked = isSelectAll;
}
Best way I can think of is to convert the GridView's CheckBoxField to a TemplateField. Then wire up the new asp:CheckBox in your TemplateField to the CheckedChanged event. In your code-behind, you handle the CheckedChanged event, then when any of the checkboxes change to unchecked, you can toggle your "check all" checkbox.
Look at this code. hope this will help you
<div>
<asp:CheckBox ID="chkSelectAll" runat="server" />
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" oncheckedchanged="chkSelect_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
bool isFound = false;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox chkSelect = gvr.FindControl("chkSelect") as CheckBox;
if (chkSelect.Checked == false)
{
isFound = true;
break;
}
}
if (isFound)
{
chkSelectAll.Checked = false;
}
else
{
chkSelectAll.Checked = true;
}
}
The following code should work. I tested it.
Javascript:
<script type="text/javascript">
function OnOneCheckboxSelected(chkB) {
var IsChecked = chkB.checked;
var Parent = document.getElementById('gridFileList');
var cbxAll;
var items = Parent.getElementsByTagName('input');
var bAllChecked = true;
for (i = 0; i < items.length; i++) {
if(items[i].id.indexOf('cbxSelectAll') != -1){
cbxAll = items[i];
continue;
}
if (items[i].type == "checkbox" && items[i].checked == false) {
bAllChecked = false;
break;
}
}
cbxAll.checked = bAllChecked;
}
function SelectAllCheckboxes(spanChk) {
var IsChecked = spanChk.checked;
var cbxAll = spanChk;
var Parent = document.getElementById('gridFileList');
var items = Parent.getElementsByTagName('input');
for (i = 0; i < items.length; i++) {
if (items[i].id != cbxAll.id && items[i].type == "checkbox") {
items[i].checked = IsChecked;
}
}
}
</script>
ASPX Markup:
<asp:TemplateField HeaderText="Select">
<HeaderTemplate>
<asp:CheckBox ID="cbxSelectAll" OnClick="javascript:SelectAllCheckboxes(this);" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox OnClick="javascript:OnOneCheckboxSelected(this);" ID="cbxSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Above code I modifiyed it, if user unchecked the child rows of grid. grid header will automatically uncheck.
<script type="text/javascript">
function UncheckHeader(headerchk) {
var gvcheck = document.getElementById('gvdetails');
var inputs = gvcheck.rows[0].getElementsByTagName('input');
inputs[0].checked = false;
}
function SelectAll(headerchk) {
var gvcheck = document.getElementById('gvdetails');
var i;
// if true checked all checkboxes
if (headerchk.checked) {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = true;
}
}
//if condition fails uncheck all checkboxes in gridview
else {
for (i = 0; i < gvcheck.rows.length; i++) {
var inputs = gvcheck.rows[i].getElementsByTagName('input');
inputs[0].checked = false;
}
}
}
</script>
<asp:GridView ID="gvdetails" runat="server" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkheader" runat="server" onclick="javascript:SelectAll(this)" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkchild" runat="server" onclick="javascript:UncheckHeader(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
more details here
On my webpage, I have a CheckBoxList and a single checkbox. When I click on the check box, all the Check Boxes in the CheckBoxList should get checked. My CheckBoxList has to be under Bodycontent placeholder because that's how the layout of webpage is, and I kept the script in the same placeholder.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
function select(ch) {
var allcheckboxes = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName("input");
for (i = 0; i < allcheckboxes.length; i++)
allcheckboxes[i].checked = ch.checked;
}
</script>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>Item A</asp:ListItem>
<asp:ListItem>Item B</asp:ListItem>
<asp:ListItem>Item C</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="allCheck" onclick="select(this)" runat="server" Text="Select all" />
<br />
</asp:Content>
The above doesn't do anything. On clikcing on the checkbox nothing happens! I have been stuck on this small issue from quite long and not able to do the same. Any suggestions what's wrong?
change the name of your function to something else; it will work
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
function select1(ch) {
var allcheckboxes = document.getElementById('<%=CheckBoxList1.ClientID %>').getElementsByTagName("input");
for (i = 0; i < allcheckboxes.length; i++)
allcheckboxes[i].checked = ch.checked;
}
</script>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>Item A</asp:ListItem>
<asp:ListItem>Item B</asp:ListItem>
<asp:ListItem>Item C</asp:ListItem>
</asp:CheckBoxList>
<asp:CheckBox ID="allCheck" onclick="select1(this)" runat="server" Text="Select all" />
<br />
</asp:Content>
try like this..
function UnCheckAll(isCheck) {
var theForm = document.forms['yourFormName'];
if (!theForm) {
theForm = document.form1;
}
var length = theForm.elements.length;
for (var i = 0; i < length; i++) {
if (theForm.elements[i].type == "checkbox") {
if (theForm.elements[i].id != "allCheck") {
if (theForm.elements[i].disabled == false) {
theForm.elements[i].checked = isCheck.checked;
}
}
}
}
}