How to use JavaScript on CheckBxes in ASP.NET


In this article we will see how to apply a JavaScript for CheckBox control which will find all the checkbox control in the form and if no one is checked then it will prompt to select at least one checkbox otherwise delete the record accordingly.

In the form we have taken 4 checkbox, 4 textbox and a button.
below is the design code:



<asp:CheckBox ID="CheckBox1" runat="server" Text="a" />
<asp:TextBox ID="TextBox1" runat="server">a</asp:TextBox>
<br />
<asp:CheckBox ID="CheckBox2" runat="server" Text="b" />
<asp:TextBox ID="TextBox2" runat="server">b</asp:TextBox>
<br />
<asp:CheckBox ID="CheckBox3" runat="server" Text="c" />
<asp:TextBox ID="TextBox3" runat="server">c</asp:TextBox>
<br />
<asp:CheckBox ID="CheckBox4" runat="server" Text="d" />
<asp:TextBox ID="TextBox4" runat="server">d</asp:TextBox>
<br />
<br />
<asp:Button ID="btndelete" runat="server" Text="Delete" OnClientClick="return ShouldDelete();"
OnClick="btndelete_Click" />
</div>




Below is the javascript which will check if checkbox is checked then it will delete the
value of textbox. i.e. if first checkbox is checked then it will delete value of first
textbox and accordingly for other.


function ShouldDelete() {
var IsDelete;
IsDelete = true;

for (i = 0; i < document.forms[0].elements.length; i++) {
var elm = document.forms[0].elements[i];
var Objname = elm.name;
if (elm.type == 'checkbox') {
if (elm.checked == true) {
IsDelete = true;
var agree = confirm("Are you sure you want to mark this record as deleted ?");
if (agree)
return true;
else
return false;
}
else {
IsDelete = false;
}
}
}
if (IsDelete == false) {
alert("Atleast one record must be selected to Delete");
return false;
}
else {

var agree = confirm("Are you sure you want to mark this record as deleted ?");
if (agree)
return true;
else
return false;
}
}
</script>


and below is the code on button click:

protected void btndelete_Click(object sender, EventArgs e)
{
if (CheckBox1.Checked)
TextBox1.Text = "";
if (CheckBox2.Checked)
TextBox2.Text = "";
if (CheckBox3.Checked)
TextBox3.Text = "";
if (CheckBox4.Checked)
TextBox4.Text = "";


CheckBox1.Checked = false;
CheckBox2.Checked = false;
CheckBox3.Checked = false;
CheckBox4.Checked = false;
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: