Using onCheckedChanged with PopupControlExtender and want to prevent popup when unchecking - c#

I am still reasonably new to this and have tried to find an answer, so hopefully I am not repeating this.
I am using ASP.NET and have a checkbox control that brings up a popup box when it's changed, using the onCheckedChanged method. This popup box has some info in it and a 'Close' button which successfully closes the popup.
What I want is to prevent the popup appearing if the checkbox is being unchecked. I currently have the onCheckedChanged calling a code behind method which cancels the extender call if the control is not checked, but the popup quickly appears before it is closed. How can I prevent it this?
This is the appropriate page code:
<div class="row" id="divDDMandate" runat="server">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:CheckBox ID="chkDDMandate" Width="20px" Visible="true" runat="server" AutoPostBack="true"
OnCheckedChanged="clientchkDDMandateChanged(this);" on />
<asp:Literal ID="ltlDDMandate" runat="server">Direct Debit Mandate (by post)</asp:Literal>
<asp:PopupControlExtender ID="chkDDMandate_PopupControlExtender" runat="server"
DynamicServicePath="" Enabled="true" PopupControlID="PanelDDMandateDownload"
TargetControlID="chkDDMandate"
Position="Bottom" OffsetX="-20" OffsetY="10" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
...and this is my code behind method:
protected void chkDDMandateChanged(object sender, EventArgs e)
{
//Cancel the panel if unchecking
if ((!chkDDMandate.Checked) && chkDDMandate_PopupControlExtender.Enabled)
{
chkDDMandate_PopupControlExtender.Cancel();
}
}
I would be grateful for any help.
Cheers

Remove AutoPostBack="true" from the chkDDMandate checkbox and add script below after the ScriptManager control:
<script type="text/javascript">
function pageLoad() {
var extender = $find("<%= chkDDMandate_PopupControlExtender.ClientID %>");
extender.remove_showing(onPopupShowing);
extender.add_showing(onPopupShowing);
}
function onPopupShowing(sender, args) {
var checkBoxChecked = $get("<%= chkDDMandate.ClientID %>").checked;
args.set_cancel(!checkBoxChecked);
}
</script>

After Yuriy provided me with the event handler, I had to resort to using hidden fields to keep track of the visibility of the popup and the checkbox.
This was because I didn't want the popup to appear when the tick was being removed and the fact that the onClick method used the setting the checkbox control was being set to, whereas the onShowing method was using the current visible setting of the control. I had to use the hidden fields to keep the visibilty settings and update them at the time I wanted.
I'm surprised that the _visible property of the popup extender was always set to 'false', so I couldn't use that either.
This may be a bit of a hack, but this is my current javascript code for anyone that is interested:
<script type="text/javascript">
function pageLoad() {
// Attach an event handler for over-riding the showing Popup.
var extender = $find("PopupControlExtenderBehaviorID");
extender.remove_showing(onPopupShowing);
extender.add_showing(onPopupShowing);
// Initialise the hidden fields based on the page status after refresh.
var hfPopup = $get("ctl00_body_PopupVisibleID");
var hfCheckbox = $get("ctl00_body_CheckboxChecked");
// Popup will always be hidden on page refresh
hfPopup.value = "Hidden";
hfCheckbox.value = $get("ctl00_body_chkDDMandate").checked;
}
function onPopupShowing(sender, args) {
// This function will over-ride the Popup showing if applicable.
var popupVisible = $get("ctl00_body_PopupVisibleID");
var checkboxChecked = $get("ctl00_body_CheckboxChecked");
// If Popup hidden and 'tick' being taken out of the Checkbox, don't show the Popup.
if (popupVisible.value == "Hidden" && checkboxChecked.value == "true") {
args.set_cancel(true);
}
else if (popupVisible.value == "Hidden") {
popupVisible.value = "Visible";
}
else {popupVisible.value = "Hidden";}
}
function OnClientClickCheck(o) {
// This function will set the Hidden field value of Checkbox.
// This is because when the OnClick method reads the control checkbox value it uses the value it's
// being set to; whereas, the onPopupShowing method uses the value it is currently displaying!
var pce = $find('PopupControlExtenderBehaviorID');
var checkboxChecked = $get("ctl00_body_CheckboxChecked");
var isChecked = o.checked;
if (isChecked) {
// isChecked is what it is being changed to...
checkboxChecked.value = "false";
}
else {
checkboxChecked.value = "true";
}
pce.showPopup();
}
</script>
Thanks for the help in getting here.

Related

Hidden field not getting set Ajax AutoCompleteExtender OnClientItemSelected

I'm trying to use the following Ajax AutoCompleteExtender:
<asp:TextBox runat="server" Width="300" ID="tbxItem" CssClass="NormalUpper" />
<asp:AutoCompleteExtender ID="autoCompleteExtenderItemName" runat="server"
MinimumPrefixLength="1" ServicePath="../Services/AutoCompleteSpecialOrders.asmx"
ServiceMethod="GetItems" CompletionInterval="100"
Enabled="True" TargetControlID="tbxItem" CompletionSetCount="15" UseContextKey="True"
EnableCaching="true" ShowOnlyCurrentWordInCompletionListItem="True"
CompletionListCssClass="dbaCompletionList"
CompletionListHighlightedItemCssClass="AutoExtenderHighlight"
CompletionListItemCssClass="AutoExtenderList" DelimiterCharacters="">
OnClientItemSelected="ItemSelected"
</asp:AutoCompleteExtender>
<asp:HiddenField runat="server" ID="hiddenItemId" />
We're using Master Pages (asp.net 4.0), User Controls and UpdatePanels. I'm having difficulty getting the OnClientItemSelected="ItemSelected" JavaScript/Jquery function to work. Here is the ScriptManagerProxy:
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" >
<Scripts>
<asp:ScriptReference Path="../common/script/AutoExtend.js"/>
</Scripts>
</asp:ScriptManagerProxy>
And here is the contents of AutoExtend.js (JavaScript & Jquery):
//function ItemSelected(sender, eventArgs) {
// var hdnValueId = "<%= hiddenItemId.ClientID %>";
// document.getElementById(hdnValueId).value = eventArgs.get_value();
// alert(hdnValueId.value);
// document.getElementById("tbxCatalogQty").focus();
// This try didn't work for me}
function ItemSelected(sender, e) {
var hdnValueId = $get('<%=hiddenItemId.ClientID %>');
hdnValueId.value = e.get_value();
alert(hdnValueId.value);
document.getElementById("tbxCatalogQty").focus();
} //Neither did this one.
The alert DOES show the correct value from our WebService drop-down-type list! I just can't seem to set the hidden field to this value so I can use it in the code-behind later. It always shows as "" when run in the debugger. Also, the .focus() method doesn't set the focus to the tbxCatalogQty field like I would like. I've also tried this with single-quotes and that didn't change anything either.
In my code behind, I've tried accessing the hidden field as follows without any luck:
//var itemId = Request.Form[hiddenItemId.Value];
var itemId = hiddenItemId.Value;
I've seen a couple of similar posts out there: 12838552 & 21978130. I didn't see where they mentioned anything about using Master Pages and User Controls and inside of an UpdatePanel (not sure that makes any difference, however).
With the help of a friend, he just figured out the solution. First, we did a JavaScript postback, passing in the value like this:
function ItemSelected(sender, e) {
var hdnValueId = $get('<%=hiddenItemId.ClientID %>');
hdnValueId.value = e.get_value();
window.__doPostBack('UpdatePanelOrdersDetails', hdnValueId.value);
}
Then, in the ASP:Panel that contained the AutoCompleteExtender, we added the "Onload="pnlInputCat_Load" parameter.
<asp:Panel ID="pnlInputCat" runat="server" OnLoad="pnlInputCat_Load">
Then, in the code behind, we added the pnlInputCat_Load method to look like this:
protected void pnlInputCat_Load(object sender, EventArgs e)
{
var theId = Request["__EVENTARGUMENT"];
if (theId != null && !theId.Equals(string.Empty))
{
Session["ItemCode"] = Request["__EVENTARGUMENT"];
tbxCatalogQty.Focus();
}
}
There certainly might be better ways to make this work, but I now have the ItemCode in a session variable for later access and I could then set focus on the Catalog Qty textbox.
Thanks for anyone who tried to understand/answer the above question.

Fire Serverside event from javascript

i have hiddentfield whose value is changing on javascript.
I just wanted to fire serverside event valuechanged event of hiddenfield when its value changed from javascript.
I tried with :
__doPostBack('hfLatitude', 'ValueChanged');
But giving me error :
Microsoft JScript runtime error: '__doPostBack' is undefined
Is there any other alternative for this?
Please help me.
In javascript, changes in value to hidden elements don't automatically fire the "onchange" event. So you have to manually trigger your code that is already executing on postback using "GetPostBackEventReference".
So, with a classic javascript approach, your code should look something like in the example below.
In your aspx/ascx file:
<asp:HiddenField runat="server" ID="hID" OnValueChanged="hID_ValueChanged" Value="Old Value" />
<asp:Literal runat="server" ID="litMessage"></asp:Literal>
<asp:Button runat="server" ID="btnClientChage" Text="Change hidden value" OnClientClick="ChangeValue(); return false;" />
<script language="javascript" type="text/javascript">
function ChangeValue()
{
document.getElementById("<%=hID.ClientID%>").value = "New Value";
// you have to add the line below, because the last line of the js code at the bottom doesn't work
fValueChanged();
}
function fValueChanged()
{
<%=this.Page.GetPostBackEventReference(hID, "")%>;
}
// the line below doesn't work, this is why you need to manually trigger the fValueChanged methiod
// document.getElementById("<%=hID.ClientID%>").onchange = fValueChanged;
</script>
In your cs file:
protected void hID_ValueChanged(object sender, EventArgs e)
{
litMessage.Text = #"Changed to '" + hID.Value + #"'";
}
Quick and Dirty:
Simply put a asp button on form. Set it display:none.
<asp:Button id="xyx" runat="server" style="display:none" OnClick="xyx_Click" />
On its click event call any server side event.
protected void xyx_Click(o,e)
{
//you server side statements
}
To call its from JS use as below:
<script>
function myserverside_call()
{
var o = document.getElementById('<%=xyx.ClientID%>');
o.click();
}
function anyotherjsfunc()
{
//some statements
myserverside_call();
}
</script>
First way is to use HiddenField.ValueChanged Event.
If you want to also watch this varible in Client Side just use this:
$('#hidden_input').change(function() {
alert('value changed');
});
Second way is to assign value to Varible:
$('#hidden_input').val('new_value').trigger('change');

Button onClick doesn't work if it is inside of DIV in ASP.NET

I have a div like as :
<div id="specific">
<table cellpadding="2" border="0">
<tr><td>Choose category</td><td><select id="list_categories" runat="server"></select></td><td><asp:RequiredFieldValidator ControlToValidate="list_categories" runat="server" Display="Static" ErrorMessage="Select category" ID="verify_category"></asp:RequiredFieldValidator></td></tr>
<tr><td>Link name : </td><td><asp:TextBox ID="link_name" runat="server"></asp:TextBox></td><td><asp:RequiredFieldValidator ControlToValidate="link_name" runat="server" Display="Static" ErrorMessage="Provide a name for link" ID="verify_link_name"></asp:RequiredFieldValidator></td></tr>
<tr><td>Link url : </td><td><asp:TextBox ID="link_url" runat="server"></asp:TextBox></td><td><asp:RegularExpressionValidator ID="verify_url" runat="server" ControlToValidate="link_url" Display="Static" ErrorMessage="Invalid link. Must be as http://www.stabiplan.com" ValidationExpression="^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$"></asp:RegularExpressionValidator></td></tr>
<tr><td>Link description</td><td><asp:TextBox ID="link_descr" runat="server"></asp:TextBox></td><td><asp:RequiredFieldValidator ControlToValidate="link_descr" runat="server" ID="verify_descr" Display="Static" ErrorMessage="Provide a link description"></asp:RequiredFieldValidator></td></tr>
<tr><td colspan="2"><center><asp:Button runat="server" ID="add_link_process" Text="Add link" OnClick="add_link_function" /></center></td></tr>
</table>
</div>
and the function from CodeBehind.cs
protected void add_link_function( object sender, EventArgs e ) {
BusinessLayerArcht layer = LoadDataFromBL();
if ( layer.add_link( link_name.Text, link_url.Text, link_descr.Text, list_categories.Value.ToString() ) ) {
messages.Text = "Link added successfully";
LoadTree( tree );
} else {
messages.Text = "Link could not be added !";
}
}
When I click on the button, nothing happens. Why ?
If I remove DIV block and let the code inside the <table>, button click event works.
Thank you
I highly doubt it has anything to do with the div element. Usually, when a button does nothing it's because validation is preventing the postback. To test this, set the CausesValidation property to false on the Button and try again.
Have you tried adding a breakpoint to the add_link_function method to check whether its being triggered at all?
Regarding your validation issue, you can add ValidationGroup to your Validation controls as well as your Button. This way, only validation controls with a matching group name as the triggered button, will be actioned.
may you have to change the property of button " UseSubmitBehavior " to false
This is is a total guess, but it's possible the 'div' is sitting on top of your table and preventing the click getting to the button, you could try some Javascript code like this -
function getActivatedObject(e) {
var obj;
if (!e) {
obj = window.event.srcElement;
} else if (e.srcElement) {
obj = e.srcElement;
} else {
obj = e.target;
}
return obj;
}
function addEventHandler(obj, eventName, handler) {
if (document.attachEvent) {
obj.attachEvent("on" + eventName, handler);
} else if (document.addEventListener) {
obj.addEventListener(eventName, handler, false);
}
}
to work out which element was getting the click event.
Code from - How do I know which element was clicked?
In the properties of that button, set OnClientClick as the name of the function you are calling on "onClick".
It worked for me.

Get variable & keep changes after postback

This question is related to: Hide div on clientside click
The issue I am having is that after postback event from asp.net happens onClick any clientside changes made reset how can I keep the client side changes I am making.
Second question how can I get a variable from code behind and pass it into my javascript to perform a comparison.
Html:
<div runat="server" id="someDiv1" enableviewstate="true" >
<asp:LinkButton OnClientClick="Show_Hide_Display()"
ID="lbtnDiv1"
runat="server"
CausesValidation="true"
OnClick="lbtn_onClickServer">
</asp:LinkButton>
</div>
<div runat="server" class="tick" id="div2" style="display:none;" enableviewstate="true">
</div>
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("<%=someDiv1.ClientID%>");
var div2 = document.getElementById("<%=div2.ClientID %>");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
div2.style.display = "block";
}
else {
div1.style.display = "block";
div2.style.display = "none";
}
}
</script>
The OnClick event causes a postback like it should, on this occassion it checks if users, chosen username is available.
If it is available show a tick, if it isn't error.
I got the error working and am trying to program the tick on client side.
So OnClientClick I am able to toggle between some text and a tick. So I need to:
Get the bool result from code behind
After postback keep tick (if username is available)
I am almost there but can't quite figure the last two points out.
If you are using an UpdatePanel in your page, and assuming that div which you are trying to toggle is outside the control, you can always inject javascript on a partial postback:
Like for e.g. on your button's click event which executes on a partial postback make a call to ScriptManager.RegisterClientScriptBlock() --> How to retain script block on a partial postback?
Alternatively, you can append an end request handler. This is some javascript which should run after the partial postback. --> ASP.NET Register Script After Partial Page Postback (UpdatePanel)
The answer for the both questions lies of checking the boolean value send from the code behind.
1-----.in code-behind c#
protected void Page_Load(object sender, System.EventArgs e)
{
var linkbtn = (Button)Page.FindControl("lbtnDiv1");
linkbtn .Attributes.Add("onClick", "Show_Hide_Display('" + parameter+ "')");
}
2------- change your javascript
function Show_Hide_Display(parameter)
{
if( paramater=='true')
{
----your logic---
}
else
{
----your logic
}
}

JavaScript for GridView row TemplateFields

I'm creating a program where, in each GridView row, there is a checkbox and a textbox, which are unchecked and disabled by default respectively. When the checkbox is ticked, I need to fire a bit of JavaScript to enable that textbox, and vice versa for when is unticked. So far I am doing this:
JS:
<script type="text/javascript">
function onholdev(index) {
var chk = document.getElementById('<%=grdCons.Rows[index].FindControl("chkHold").ClientID %>');
var txt = document.getElementById('<%=grdCons.Rows[index].FindControl("txtReason").ClientID %>');
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
C# (RowDataBound event)
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");
But in the JS, it's saying the 'index' variable does not exist, in the first line of the function (that begins with var chk). Am I doing this right?
the problem is that index is inside the string while it should be a parameter, this fixes it :
var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
the same goes for the other line
Since the check box will render as input we can able to find it by using the $('.check input') and since it is added dynamically we need to use jquery bind to add the click function to the check box.So in this I am getting the checked control by chk = $('.check input');.Each time when user checks a check box the function calls .I am here setting the visibility to none of all text box and when the user click it will find the next control and removing the class .hde using $(this).parent().next().removeClass('hide');.So the textbox will be visible next to the checkbox.
In your case I think by default you will make textbox disabled=false
.hide is used to set visiblity false.you can do disabling by adding attribute disabled to the textbox
css
.hide
{
display: none;
}
Designer Code
<ItemTemplate>
<asp:CheckBox ID="cbEnergyItems" runat="server" CssClass="check" />
<input type="text" id="txtQty" style="width: 25px" class="hide"
value="0" runat="server" />
<%# Eval("something") %>
</ItemTemplate>
Jquery
$('.check input').bind("click", function() {
var chk = $('.check input');
if ($(this).attr('checked')) {
//$(this).parent().next().removeClass('hide'); //removing the class to visible. you can do removing the attribute
$(this).parent().next().removeAttr("disabled");
if ($(this).parent().next().val() == ""0"")
showStatus(true, "Please enter the quantity");
}
else {
$(this).parent().next("disabled","disabled").
// $(this).parent().next().addClass('hide');
}
});
I think this will solve your problem.
Thanks all for your help, I sort of 'solved' it by not doing it serverside instead. Bit lazy but saves a lot of JS headaches.

Categories

Resources