0

I have some Javascript that works perfectly before a postback happens in ASP.Net, however when a postback event occurs from a button click the script no longer runs.

this is the code I am using

function displayCheckboxInSubject() {
    var CountSelectedCB = [];
    console.log("in displayCheckBoxInSubject with loader");
    $(".subjectCB").on("change loader", function () {
    //$(".subjectCB").change(function () {
        selectedCB = [];
        notSelectedCB = [];
        CountSelectedCB.length = 0;
        $(".subjectCB").each(function () {
            //alert("in here two")
            if ($(this).find("input").is(":checked")) {
                //alert("in here three")
                CountSelectedCB.push($(this).find("input").val());
            }
        });

        $("#txtSubject").val(CountSelectedCB.join(", "));
    }).trigger("loader");

}

$(document).ready(displayCheckboxInSubject);

I would be grateful if someone could point me in the right direction of how to resolve this.

thanks

Simon

Simon Price
  • 3,011
  • 3
  • 34
  • 98

1 Answers1

0

It is because document.ready() is not executed after a postback.

Microsoft suggest using PageRequestManager to set up a request handler. But you can alternatively initialise your control from the back-end and fire it that way.

I can't take credit for it, but please see this answer: answered on SO

UPDATE: Can you use an UpdatePanel? That should make it work.

<script type="text/javascript">
  function pageLoad() {
    $('#TextBox1').unbind();
    $('#TextBox1').datepicker(); 
  }
</script>

<asp:ScriptManager runat="server" />

<asp:UpdatePanel runat="server">
  <ContentTemplate>
    <asp:Button runat="server" ID="Button1" />
    <asp:TextBox runat="server" ID="TextBox1" />
  </ContentTemplate>
</asp:UpdatePanel>

Basic example from Encosia

Community
  • 1
  • 1
VictorySaber
  • 3,084
  • 1
  • 27
  • 45
  • where do i need to put this instead? or should i just remove it? – Simon Price Oct 26 '15 at 15:11
  • this isnt working for me, nor am i doing an async postback – Simon Price Oct 26 '15 at 15:20
  • maybe - what I am trying to do is when a user clicks send on an asp.net webform to send data to a database, if this fails, the page was posting back and not keeping the values. The page is now keeping the values, but now has stopped the javascript working. So, if I use an update panel, where would I use this? would I put my checkbox list in the panel, or would i use it else where? – Simon Price Oct 26 '15 at 15:42
  • Put the UpdatePanel in your form, and your controls inside that. See this link: http://www.asp.net/web-forms/overview/older-versions-getting-started/aspnet-ajax/understanding-asp-net-ajax-updatepanel-triggers – VictorySaber Oct 26 '15 at 15:52