ASP.net hiding panel using javascript - asp.net

I have a radioButtonList with 2 items in it. A radiobutton with a "Yes" value and a radionButton with a "No" value.
Below that I have a panel which I want made visible when "Yes" radioButton is selected and hidden when "No" is selected. I had originally implemented this using the AutoPostBack attribute but I want to do it in Javascript so that it doesn't cause a postback. Here's the code. Any help would be greatly appreciated.
<asp:RadioButtonList ID="rbl1" runat="server" onClick="changed(this);" >
<asp:ListItem Value="Yes">Yes</asp:ListItem>
<asp:ListItem Value="No">No</asp:ListItem>
<asp:Panel ID="panel1" runat="server">
<--other controls here -->
</asp:Panel>
function changed(rbl) {
//not sure what to put in here
}
Thanks in advance,
Zaps

Here is a quick example I made up:
<!-- Used grouped radio buttons instead of the RadioButtonList as it is harder to deal with -->
<asp:RadioButton ID="rbYes" runat="server" Text="Yes" GroupName="YourGroupName" Checked="true" />
<asp:RadioButton ID="rbNo" runat="server" Text="No" GroupName="YourGroupName" />
<br /><br />
<!-- Use a div instead of a panel. Panels are just glorified divs. -->
<div id="divTest">
This is a test
</div>
<script type="text/javascript">
$(document).ready(function()
{
$('#<%= rbYes.ClientID %>').click(function() { $('#divTest').show(); });
$('#<%= rbNo.ClientID %>').click(function() { $('#divTest').hide(); });
});
</script>

function OnclickPanelHide() {
if (this.value == "No") {
document.getElementByID('<%=panel1.ClientID%>').style.display = "none";
}
else {
document.getElementByID('<%=panel1.ClientID%>').style.display = "block";
}
}
</script>
Raja There is some bug in your code i just removed it

If you add a class or determine the real id of "panel1", you can use jQuery to hide it easily:
$('idOfPanel').hide();
Or you without using jQuery, using the id of the div/panel:
idOfPanel.style.display = "none";
To redisplay:
$('idOfPanel').show();
Or
idOfPanel.style.display = "block";

try this:
if (this.value == "No")
{
document.getElementByID('<%=panel1.ClientId%').style.display = "none";
}
else
{
document.getElementByID('<%=panel1.ClientId%').style.display = "block";
}
Hope it helps.

if you don't mind doing a partial postback, you can also throw your code into an UpdatePanel (assuming that you don't want to postback so that the entire page doesn't have to go through a page life-cycle).

Related

The value of checkbox is wrong in asp.net

I am using asp.net. I want to show unchecked checkbox but in the browser the status of the checkbox is true and I have set the checkbox.checked= false in serverside code but it displays checked in the browser.
Here is my code
{<asp:CheckBox ID="SendNotificationCheckBox" runat="server" Checked="false" Enabled="false" oncheckedchanged="SendNotificationCheckBox_CheckedChanged" AutoPostBack="true"/>}
I tried this piece of code in server side:
{ protected void SendNotificationCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (SendNotificationCheckBox.Checked == true)
{
NotificationPanel.Visible = true;
NotificationMessageTextBox.Text = "Business Listing Named:" + BusinessNameLabel.Text.Trim() + " Will Be Expired On" + NextVerificationDateLabel.Text.Trim() + ".Contact Us To Renew it.";
}
else if (SendNotificationCheckBox.Checked == false)
{
NotificationPanel.Visible = false;
}
}}
I know this isn't what you asked, but I think JavaScript / JQuery would be best for this kind of things. Place the following code in the head of your page
<script type="text/javascript">
function toggleVisibility(cb) {
var x = document.getElementById("NotificationPanel");
x.style.display = cb.checked ? "block" : "none";
}
</script>
and in your Checkbox
<asp:CheckBox ID="SendNotificationCheckBox" runat="server" Checked="false" onclick="toggleVisibility(this);"/>
<asp:Panel runat="server" ID="NotificationPanel" style="display: none;">
skjhaskjf
</asp:Panel>
or if You want to use JQuery, add this in your Head
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#SendNotificationCheckBox").click(function () {
$(this).is(':checked') ? $("#NotificationPanel").show() :
$("#NotificationPanel").hide();
});
});
</script>
and your checkbox
<asp:CheckBox ID="SendNotificationCheckBox" runat="server" Checked="false"/>
<asp:Panel runat="server" ID="NotificationPanel" style="display: none;">
skjhaskjf
</asp:Panel>
Here is the solution to your problem as you wanted.
You were unchecking the textbox and disabling it in PageLoad. If you do that, every time when the control comes to the server, PageLoad will be executed, and the checkbox will be be disabled. and after executing the pageload, the event 'SendNotificationCheckBox_CheckedChanged' will be executed.
Since the Checkbox is unchecked in the pageload, the code you have written if Checkbox is checked will be of no use. So, you have to check whether the page is loading for the first time. If so, Uncheck the checkbox or else don't.
You have to Do that by Checking for IsPostBack property by
If(!IsPostBack)
{
CheckBoxID.Checked=false;
CheckBoxID.Enabled=false;
}
If your checkbox is inside update panel,
then you need to update your update panel..

ASP .NET - Submit on Enter - Prevent 'defaultbutton' when other button has focus

I have a search form consisting of the following...
<asp:Panel DefaultButton="btnSearch" ... >
[...search criteria fields...]
<asp:Button ID="btnReset" OnClick="btnReset_Click" ... />
<asp:Button ID="btnSearch" OnClick="btnSearch_Click" ... />
</asp:Panel>
The desired behaviour is that pressing the Enter key should invoke btnSearch_Click (which is working thanks to the DefaultButton attribute in the asp:panel)
The problem is that when btnReset has focus, pressing Enter should invoke btnReset_Click instead (which it doesn't - it's always btnSearch).
Is this easily achievable somehow, or am I going to have to hack up some bespoke JS to intercept .NET's defaultButton event handler?
Thanks in advance.
ETA: Here's a reusable solution I went with based on HenryChuang's accepted answer below.
Add a custom attribute preventDefaultButton to panels.
<asp:Panel DefaultButton="btnSearch" preventDefaultButton="btnReset" >
[...search criteria fields...]
<asp:Button ID="btnReset" OnClick="btnReset_Click" ... />
<asp:Button ID="btnSearch" OnClick="btnSearch_Click" ... />
</asp:Panel>
Run the following jQuery on pageload.
$("div[preventDefaultButton]").each(function () {
var div = $(this);
var keypressEvent = div.attr("onkeypress");
var btn = $("input[id$=" + div.attr("preventDefaultButton") + "]");
btn.on("focus", { div: div }, function (event) {
event.data.div.attr("onkeypress", "");
});
btn.on("blur", { div: div, keypressEvent: keypressEvent }, function (event) {
event.data.div.attr("onkeypress", event.data.keypressEvent);
});
});
see the panel generate html
<div id="yourPanelClientID" onkeypress="javascript:return WebForm_FireDefaultButton(event, 'btnSearch')">
so, when btnReset onfocus we break onkeypress event of Panel, add below to btnReset,
remember when btnReset onblur, change Panel keypress to oringinal
onfocus="document.getElementById('yourPanelClientID').onkeypress = '';"
onblur="funA();"
function funA() {
document.getElementById('yourPanelClientID').onkeypress = function () { return WebForm_FireDefaultButton(event, "btnSearch") };
}
like this
<asp:Button ID="btnReset"
onfocus="document.getElementById('yourPanelClientID').onkeypress = '';"
onblur="funA();"
onclick="btnReset_Click" .../>
you need to change DefaultButton attribute of your panel but this will work for only one at a time, better way would be to have Javascript to capture enter event and process accordingly.
One way can be having multiple panels, have a look at http://www.jstawski.com/archive/2008/09/23/multiple-default-buttons.aspx

disable button in ascx page prior to postback

How do I disable a button in an ascx page? I know how to do it on an aspx page with:
btnSave.Attributes.Add("onclick",
"this.disabled=true;this.value='Please Wait...';needToConfirm=false;" +
ClientScript.GetPostBackEventReference(btnSave, "").ToString());
But the ClientScript function is not present in the ascx page.
You don't need the ClientScript in code behind, you can also have it directly in the button tag as OnClientClick attribute:
<asp:Button id="btnSave" runat="server" OnClientClick="this.disabled=true; this.value='Please Wait...'; needToConfirm=false;" Text="Save" />
You can access the ClientScript property using Page.ClientScript from your user control (ascx).
you can access ClientScript through the Page property of your control
Page.ClientScript.GetPostBackEventReference(btnSave, "")
Did you try: Page.ClientScript.GetPostBackEventReference?
Here's how I fixed the problem. In every page, I have three divs:
<div align="center" id="divWait" style="display:none"><asp:Label ID="lblSaveorCancel" runat="server"></asp:Label></div>
<div style="display:block" id="divMain">
---- page actual content here ------
</divMain>
<div id="divBut" style="text-align:center;display:block">
<asp:button id="SaveBtn" runat="server" CssClass="button" Text="Save" OnClientClick="return Validate('save');"/>
<asp:button id="CancelBtn" runat="server" CssClass="button" Text="Cancel" OnClientClick="return ShowWaitDiv('cancel');"/>
</div>
And then I added scripts:
function Validate(saveorcancel) {
----- validation checks for data on the page ------
}
function ShowWaitDiv(saveorcancel) {
var div = document.getElementById(divWait.id);
div.style.display = "block";
var div1 = document.getElementById(divMain.id);
div1.style.display = "none";
var div2 = document.getElementById(divBut.id);
div2.style.display = "none";
if (saveorcancel == 'save') {
document.getElementById('<%= lblSaveorCancel.ClientID %>').innerHTML = 'Saving data, please wait...';
}
else {
document.getElementById('<%= lblSaveorCancel.ClientID %>').innerHTML = 'Redirecting, please wait...';
}
return true;
}
Simple, quick, and the user sees the result of clicking a button immediately and cannot click any buttons again.

javascript in asp.net

<asp:RadioButtonList ID="RdoBtnHasNotified" runat="server" RepeatDirection="Horizontal" AutoPostBack="True" OnSelectedIndexChanged="RdoBtnHasNotified_SelectedIndexChanged">
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0" Selected="True">No</asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="TxtHowNotified" runat="server" TextMode="MultiLine" MaxLength="100"></asp:TextBox>
I want to enable the TextBox by clicking on the RadioButtonList, without using autopostback=true. How can I do this with JavaScript?
You can use jQuery to manipulate input's enabled state (HTML translation for TextBox) or you can use ASP.NET Ajax so you can set both controls inside of update panel in this case you won't see page being reloaded on postback which must happen in order for you to change status of TextBox on some other event.
Tbh i would go with ASP.NET Ajax because my experience shows that jQuery does not work that well with ASP.NET controls when it comes to complex stuff ie. ASP.NET uses javascript for event activation which can cause either jQuery or ASP.NET not to work as you may expected.
Good luck with update panels...
Using jQuery, you can have a fairly custom result by hooking in to the changes on the radio buttons...
$("#<%= RdoBtnHasNotified.ClientID %> > input[type=radio]").change(function(){
// this function is called whenever one of the radio button list's control's change
// the $(this) variable refers to the input control that triggered the event
var txt = $("#<%= TxtHowNotified.ClientID %>");
if($(this).val()=="1") {
txt.removeAttr("disabled");
} else {
txt.attr("disabled", true);
}
});
Each ListItem renders a radio button with the same name parameter; I would suggest running the app and looking at the generated source to get an idea of what you need to do to listen for the radio button events. Essentially the ID of the radio button list is the name parameter, so you can get the group of radio buttons as (using JQuery):
$("input[name='<%= rbl.ClientID%>']").click(function() {
var tb = $("#textboxid");
//do something here; this points to the radio button
});
HTH.
Here you go:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void RdoBtnHasNotified_PreRender(object sender, EventArgs e)
{
foreach (ListItem item in RdoBtnHasNotified.Items)
item.Attributes.Add("onclick", string.Format("toggleTextBox(this,'{0}');", TxtHowNotified.ClientID));
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function toggleTextBox(radioButton, textBoxId) {
document.getElementById(textBoxId).disabled = radioButton.value != "1";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="RdoBtnHasNotified" OnPreRender="RdoBtnHasNotified_PreRender"
runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="0" Selected="True">No</asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="TxtHowNotified" runat="server" TextMode="MultiLine" MaxLength="100" Enabled="false"></asp:TextBox>
</div>
</form>
</body>
</html>
Write the code in the following way
<script type="text/javascript">
$(document).ready(function() {
$("input[name='RdoBtnHasNotified']").change(function() {
$("input[name='RdoBtnHasNotified']:checked").val() == '1' ? $('#TxtHowNotified').removeAttr("disabled") : $('#TxtHowNotified').attr('disabled', 'true');
});
});
</script>
and also disable the textbox (Enabled="false") since initialy the value of the "RdoBtnHasNotified" is "No".
$('#<%= RdoBtnHasNotified.ClientID %> > input[type=radio]').click(function()
{
var txtbox = $('#<%= TxtHowNotified.ClientID %>');
if($(this).val() == '1')
{
document.getElementById('#<%= TxtHowNotified.ClientID %>').disabled = false;
}
else
{
document.getElementById('#<%= TxtHowNotified.ClientID %>').disabled = true;
}
});
I think using change event will not fire in IE.

How to prevent ajax toolkit DropDownExtender from closing on click?

I have the code below to implement a dropdownlist with checkboxes. My problem is that every time i click a checkbox the dropdownlist closes and i need to reopen it to select more checkboxes. How do i make it so the dropdownlist dosn't close until i click off of it?
<asp:Panel ID="pnl_Items" runat="server" BorderColor="Aqua" BorderWidth="1">
<asp:CheckBoxList ID="cbl_Items" runat="server">
<asp:ListItem Text="Item 1" />
<asp:ListItem Text="Item 2" />
<asp:ListItem Text="Item 3" />
</asp:CheckBoxList>
</asp:Panel>
<br />
<asp:TextBox ID="tb_Items" runat="server"></asp:TextBox>
<ajax:DropDownExtender ID="TextBox1_DropDownExtender"
runat="server"
DynamicServicePath=""
Enabled="True"
DropDownControlID="pnl_Items" on
TargetControlID="tb_Items">
</ajax:DropDownExtender>
i prefer not altering AjaxControlToolkit. As follows:
$(document).ready(function() {
$('input[type=checkbox], label').click(function(e){
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation)e.stopPropagation();
});
});
change jquery selector to your checkboxes!
I was able to get the desired behavior by adding the following javascript that I found on this post.
var DDE;
function pageLoad()
{
DDE = $find('<%= TextBox1_DropDownExtender.ClientID %>');
DDE._dropWrapperHoverBehavior_onhover();
$get('<%= pnl_Items.ClientID %>').style.width = $get('<%= tb_Items.ClientID %>').clientWidth;
if (DDE._dropDownControl) {
$common.removeHandlers(DDE._dropDownControl, DDE._dropDownControl$delegates);
}
DDE._dropDownControl$delegates = {
click: Function.createDelegate(DDE, ShowMe),
contextmenu: Function.createDelegate(DDE, DDE._dropDownControl_oncontextmenu)
}
$addHandlers(DDE._dropDownControl, DDE._dropDownControl$delegates);
}
function ShowMe() {
DDE._wasClicked = true;
}
You will need to get the Ajax control toolkit source code and modify the DropDownExtender to behave the way you want it to. Each control has its own folder with all the files related to it's ability to function within.
Recompile, drop the new dll into your project.

Resources