How To Easily Preserve State Of DIV (Hide/Show) Between Post-backs In ASP.NET with JavaScript

                          <p>Already have an online account? <a href="#" id="aLoginForStreamlined">Log in for a streamlined experience</a>.</p>

<div id="DivLoginForm" style="display: none">
                                       Content To Hide/Show Here!
                                    </div>
 <asp:HiddenField ID="hdnLoginFormState" runat="Server" Value="0" />
                    <script>
                        // Retain Login Form expansion/contraction state between postbacks
                        $(document).ready(function () {
                            var hdnState = $('#<%=hdnLoginFormState.ClientID %>').val();
                             if (hdnState == "0") {
                                 $("[id$='DivLoginForm']").hide();
                             }
                             else {
                                 $("[id$='DivLoginForm']").show();
                             }

                             $('a#aLoginForStreamlined').click(function () {
                                 $("[id$='DivLoginForm']").toggle();

                                 var oldValue = $('#<%=hdnLoginFormState.ClientID %>').val();
                                 var newValue = (oldValue == 0) ? "1" : "0";
                                 $('#<%=hdnLoginFormState.ClientID %>').val(newValue);
                                 return false;

                             });
                         });

                    </script>
Advertisements

How To Get The Selected Value In A RadioButtonList Via JavaScript

<script type="text/javascript">
    function SelectedRBL() {
        var list = document.getElementById('<%= rblPollAnswers.ClientID %>'); //Client ID of the radiolist
        var inputs = list.getElementsByTagName("input");
        var selected;
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                break;
            }
        }
        if (selected) {
            alert(selected.value);
        }

    } 
</script>

<asp:RadioButtonList ID="rblPollAnswers" runat="server" />
<asp:Button ID="btnVote" runat="server" Text="Vote" OnClientClick="SelectedRBL();return false;" />

Nice And Simple Image Rollover Implementation

Include this script on your page
then make image rollovers simple like:

<img src="/images/ss_img.gif" oversrc="/images/ss_img_over.gif">
// This is the implementation of SimpleSwap
// by Jehiah Czebotar
// Version 1.1 - June 10, 2005
// Distributed under Creative Commons
//
// Include this script on your page
// then make image rollovers simple like:
// <img src="/images/ss_img.gif" oversrc="/images/ss_img_over.gif">
//
// http://jehiah.com/archive/simple-swap
// 


function SimpleSwap(el,which){
  el.src=el.getAttribute(which || "origsrc");
}

function SimpleSwapSetup(){
  var x = document.getElementsByTagName("img");
  for (var i=0;i<x.length;i++){
    var oversrc = x[i].getAttribute("oversrc");
    if (!oversrc) continue;
      
    // preload image
    // comment the next two lines to disable image pre-loading
    x[i].oversrc_img = new Image();
    x[i].oversrc_img.src=oversrc;
    // set event handlers
    x[i].onmouseover = new Function("SimpleSwap(this,'oversrc');");
    x[i].onmouseout = new Function("SimpleSwap(this);");
    // save original src
    x[i].setAttribute("origsrc",x[i].src);
  }
}

var PreSimpleSwapOnload =(window.onload)? window.onload : function(){};
window.onload = function(){PreSimpleSwapOnload(); SimpleSwapSetup();}

Source: http://jehiah.cz/a/simple-swap

How To Call/Inject JavaScript From CodeBehind ASP.NET

I had an issue where I was dealing with an Infragistics control (WebSpellChecker) that is only available to be triggered via clientside JavaScript. I wanted to do some server side validation before the JavaScript code to launch the WebSpellChecker dialog.

I was able todo this easily by first adding an UpdatePanel to the Page:

Example 1


        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:ImageButton ID="btnSpellCheck" runat="server" Visible="false" CssClass="img" AlternateText="SpellCheck this Page" ImageUrl="~/Images/icons/spellcheck.gif" ToolTip="SpellCheck this Page"/>
            </ContentTemplate>
        </asp:UpdatePanel>

<asp:UpdatePanel ID="UpdatePanelSpellCheck" runat="server">    
</asp:UpdatePanel>

From the code behind I validate first and if all is successful I use the ScriptManager.RegisterClientScriptBlock method pointing it to the instance of the update panel, pass it a unique key (I’m cheating by using the ClientID but if I wanted multiple scripts I could generate multiple keys) and then the JavaScript you want, and it will be executed once the update panel is done rendering.


        /// <summary>
        /// Handles the Click event of the SpellCheckButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param>
        void SpellCheckButton_Click(object sender, ImageClickEventArgs e)
        {

             // Does the user have unsaved comments?
            if (ctrlReviewJHACtrl.CtrlReviewCommentsListIntro.HasUnsavedChanges)
            {
                ((EHAP_MasterPage)Master).ErrorMessage = "Unsaved changes to summary comments.  Please either save or remove these comments.";
                return;
            }
            else if (ctrlReviewJHACtrl.ValidateComments)
            {
                ((EHAP_MasterPage)Master).ErrorMessage = "Unsaved changes to job step comments.  Please either save or remove these comments.";
                return;
            }
            else
            {
                // Otherwise present Spell Checker
                string spellCheckScript = string.Format(@"<script language='javascript'>o" + this.webSpellChecker.ClientID + ".checkTextComponent();</script>");
                ScriptManager.RegisterClientScriptBlock(UpdatePanelSpellCheck, typeof(UpdatePanel), UpdatePanelSpellCheck.ClientID, "o" + this.webSpellChecker.ClientID + ".checkTextComponent();", true);
            }  
            
        }

Another simpler example that just presents a JavaScript alert box:

Example 2

<asp:UpdatePanel ID="updPanel" UpdateMode="Conditional" runat="server">
   <Triggers>
      <asp:AsyncPostBackTrigger ControlID="btnClick" EventName="Click" />
   </Triggers>
   <ContentTemplate>
       <asp:ImageButton 
          ID="btnClick" 
          ImageUrl="button.png" 
          runat="server"
          CausesValidation="false" 
          OnClick="btnClick_Click"
          ToolTip="Click Me" 
          AlternateText="No, seriously, click me!" />
   </ContentTemplate>
</asp:UpdatePanel>

I wanted to dynamically inject some JavaScript. It’s a simple matter of registering the script. What threw me off is that you don’t use the current Page or event current ScriptManager, you call the static method on the class. It looks like this:

protected void btnClick_Click(object sender, ImageClickEventArgs e)
{
   btnClick.Text = "I was clicked."
   btnClick.Disabled = true;
   ScriptManager.RegisterClientScriptBlock(updPanel, typeof(UpdatePanel),updPanel.ClientID, "alert('wow!');",true);            
}

That’s it! Use the class, point it to the instance of your update panel, pass it a unique key (I’m cheating by using the ClientID but if I wanted multiple scripts I could generate multiple keys) and then the JavaScript you want, and it will be executed once the update panel is done rendering.

Source of Information

EDIT: Make sure that the button triggering the server-side event is wrapped in an UpdatePanel. In the first example I have two separate update panels. A more efficient way to do this would be to have just 1 like in example 2.