• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1018
  • Last Modified:

How do I stop autopostback?

ASP .NET 3.5 [C#]: I have a textbox on a aspx page. I have some j-Query script tied to the class that identifies the text box. the script does some scrubbing of the information that is entered after a person (using a card reader) swipes some data into the text box. for some reason, the page then does an auto postback and i can't stop it from doin this but I would like to. How do I do this?

the script:

            $(".studentIdInput").keyup(function () {
                var value = jQuery(this).val();
                var rSt = '';
                var lSt = '';
                if (value.length == 17) {
                    rSt = value.substring(8);
                    lSt = rSt.slice(0, -2);
                    $(".studentIdInput").val(lSt);
                }

the textbox:

<asp:TextBox ID="txtStudentIdSearchBox" type="text" class="studentIdInput" runat="server" AutoPostBack="false"/>

I get the same behavior if I were to manually enter data into the text box and hit the return key. So it appears as though, after the script has ran against the entered (swiped in) data, something is forcing a return character or it would seem that something is forcing an action that gives the same results as hitting the return key. Not sure if this helps or not.
0
Michael Sterling
Asked:
Michael Sterling
  • 5
  • 4
1 Solution
 
guru_samiCommented:
You might want to try capturing keystrokes and prevent submit on enter key: http://stackoverflow.com/questions/6497399/prevent-postback-using-javascript
0
 
Michael SterlingWeb Applications DeveloperAuthor Commented:
@guru_sami: I've tried all of the following to no avail:

            $(".studentIdInput").keyup(function () {
                var value = jQuery(this).val();
                var rSt = '';
                if (value.length == 45) {
                    rSt = value.substr(1, 8);
                    $(".studentIdInput").val(rSt);
                }
            });

            $(".studentIdInput").submit(function (e1) {
                if (e1.keyCode == 13) {          // if user is hitting enter
                    return false;
                }
            });

            $(".studentIdInput").keypress(function (e1) {
                if (e1.keyCode == 13) {          // if user is hitting enter
                    return false;
                }
            });

on both an HTML input control as well as an ASP .NET textbox. is there no way to stop the autopostback?! at least none of these techniques work.
0
 
guru_samiCommented:
If you enter the number manually and press enter while the focus in within the textbox, does the above code prevent postback?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Michael SterlingWeb Applications DeveloperAuthor Commented:
@guru_sami: no it doesn't. I also just tried this:

            $(function () {
                $(':text').bind('keydown', function (e) {
                    //on keydown for all textboxes
                    if (e.target.className == "studentIdInput") {
                        if (e.keyCode == 13) { //if this is enter key
                            e.preventDefault();
                            return false;
                        }
                        else
                            return true;
                    }
                    else
                        return true;
                });
            });

but still posting back.
0
 
guru_samiCommented:
@mike,
I just ran a sample and this one prevents postback on pressing enter:

<asp:TextBox ID="TextBox3" CssClass="txt3" runat="server" ></asp:TextBox>
$(function () {
            $(".txt3").keypress(function (e) {
                if (e.keyCode == 13) {
                    e.preventDefault();
                }
            });
        });

Open in new window

0
 
Michael SterlingWeb Applications DeveloperAuthor Commented:
@guru_sami: Not sure if it matters but did you put that function within the:

            $(document).ready(function () {

section of jQuery script? Outside of it? Or right under the declaration of the textbox?
0
 
Michael SterlingWeb Applications DeveloperAuthor Commented:
@guru_sami: this is my page right now.

<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/site.master" CodeFile="Default.aspx.cs"
    Inherits="_Default" %>

<%@ Register Src="~/UserControls/StudentsSignedInGrid.ascx" TagName="StudentsSignedInGrid"
    TagPrefix="sttc" %>
<%@ Register Src="~/UserControls/ListOfStudentsGrid.ascx" TagName="StudentsListGrid"
    TagPrefix="sttc" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="act" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <%--<script type="text/javascript" src="Scripts/jQueryPrint.js"></script>--%>
    <script type="text/javascript">
        (function ($) {
            $.print = function (message, insertType) {
                insertType = insertType || "append";
                if (typeof (message) == "object") {
                    var string = "{<br>",
                    values = [],
                    counter = 0;
                    $.each(message, function (key, value) {
                        if (value && value.nodeName) {
                            var domnode = "&lt;" + value.nodeName.toLowerCase();
                            domnode += value.className ? " class='" + value.className + "'" : "";
                            domnode += value.id ? " id='" + value.id + "'" : "";
                            domnode += "&gt;";
                            value = domnode;
                        }
                        values[counter++] = key + ": " + value;
                    });
                    string += values.join(",<br>");
                    string += "<br>}";
                    message = string;
                }

                var $output = $("#print-output");

                if (!$output.length) {
                    $output = $("<div id='print-output' />").appendTo("body");
                }

                var newMsg = $('<div />', {
                    "class": "print-output-line",
                    html: message
                });

                $output[insertType](newMsg);
            };
        })(jQuery);

        $(function () {
            $(':text').bind('keyup', function (e) {
                //on keydown for all textboxes
                if (e.target.className == "studentIdInput") {
                    if (e.keyCode == 13) { //if this is enter key
                        e.preventDefault();
                        return false;
                    }
                    else
                        return true;
                }
                else
                    return true;
            });
        });

        $(".studentIdInput").submit(function (e1) {
            if (e1.keyCode == 13) {          // if user is hitting enter
                return false;
            }
        });

        $(document).ready(function () {
            var updateWait = setTimeout(fadeUpdate, 3000);
            function fadeUpdate() {
                $("div.UpdatedMessage").fadeOut(1000);
            }

            $("a.How").hover(function () {
                var myo = $(this).offset();
                $("div.HowTo").css({ left: (myo.left - 430) + "px", top: myo.top + -40 + "px" }).show();
            }, function () {
                $("div.HowTo").hide();
            });

            $("a.SnapShot").hover(function () {
                var myo = $(this).offset();
                $("div.SnapShot").css({ left: (myo.left + 150) + "px", top: myo.top + -40 + "px" }).show();
            }, function () {
                $("div.SnapShot").hide();
            });

            /*QUINNIPIAC*/
           /*(".studentIdInput").keyup(function () {
                var value = jQuery(this).val();
                var rSt = '';
                var lSt = '';
                if (value.length == 17) {
                    rSt = value.substring(8);
                    lSt = rSt.slice(0, -2);
                    $(".studentIdInput").val(lSt);
                }
            });*/

            /*CREIGHTON*/
            $(".studentIdInput").keyup(function () {
                var value = jQuery(this).val();
                var rSt = '';
                if (value.length == 45) {
                    rSt = value.substr(1, 8);
                    $(".studentIdInput").val(rSt);
                }
            });
        });
    </script>
    <%--    <script type="text/javascript">
        function ShowCurrentTime() {
            $.ajax({
                type: "POST",
                url: "Default.aspx/SnapShotCurrentWeekTotal",
               data: '{name: "' + $("#<%=lblAthleteUid.ClientID%>")[0].value + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });
        }
    </script>--%>
    <style type="text/css">
        fieldset
        {
            margin-bottom: 1em;
        }
        input
        {
            display: block;
            margin-bottom: .25em;
        }
        #print-output, .print-output-line
        {
            width: 500px;
        }
        .print-output-line
        {
            white-space: pre;
            padding: 5px;
            font-family: monaco, monospace;
            font-size: .7em;
        }
        .studentIdInput, .prompt, .studentIdInput1, .ldapPswrd
        {
            float: left;
        }
        .studentIdInput, .studentIdInput1, .ldapPswrd
        {
            margin: -3px 9px 0 5px;
        }
        .studentFullName
        {
            float: left;
            padding: 13px 0 0 95px;
        }
        .rdBtnsAndSearch
        {
            width: 525px;
            margin: 11px 0 0 0;
        }
        .rdBtnsAndSearch, .srchContainer, .pnlButton
        {
            float: left;
        }
        .pnlButton
        {
            margin: -2px 0 0 0;
        }
        .srchContainer
        {
            width: 500px;
        }
        .notesProgram, .programAttended
        {
            margin: 10px 0 0 0;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
    <asp:HiddenField runat="server" ID="hfAccessLevel" Value='<%# Eval("Page.AccessLevel") %>' />
    <div id="MainContainer">
        <div class="MainContent">
            <div class="TableContainer">
                <div class="FiltersContainer clearfix">
                    <div class="Filters clearfix" runat="server" id="div4">
                        <div class="srchContainer">
                            <div style="float: left; width: 700px;">
                                <fieldset>
                                    <strong>Sign in / out by: </strong>
                                    <div class="rdBtnsAndSearch" runat="server" style="clear: none; width: 560px;">
                                        <ul style="background: none;">
                                            <li>
                                                <asp:RadioButton ID="rbtnStudentID" runat="server" AutoPostBack="false" Checked="false"
                                                    GroupName="AddEdit" CssClass="Radio" Text="Student ID" /></li>
                                            <%--<li>
                                        <asp:RadioButton ID="rbtnStudentFullName" runat="server" GroupName="AddEdit" CssClass="Radio"
                                            Text="Student Full Name" Checked="false" /></li>--%>
                                        </ul>
                                        <asp:TextBox ID="txtStudentIdSearchBox" type="text" class="studentIdInput" runat="server" AutoPostBack="false" />
                                        <%--<input id="Text1" type="text" class="studentIdInput"/>--%>
                                        <asp:TextBox ID="txtBxLDAPPswrd" type="text" runat="server" class="ldapPswrd" Text="P a s s w o r d"  Font-Bold="true" ForeColor="GrayText" />
                                        <%--<asp:Literal ID="ltLDAPPswrd" runat="server" Text="Password"></asp:Literal>--%>
                                        <asp:Panel ID="pnlButton" CssClass="pnlButton" runat="server">
                                            <asp:LinkButton ID="lnkbtnFindStudent" runat="server" Text="Sign In / Out" CssClass="button small green"
                                                OnClick="lnkbtnFindStudent_Click"></asp:LinkButton>
                                            <asp:LinkButton ID="lnkbtnFindStudentStudent" runat="server" Text="Sign In / Out"
                                                CssClass="button small green" OnClick="lnkbtnFindStudentStudent_Click"></asp:LinkButton>
                                            <%--<asp:LinkButton ID="LinkButton1" runat="server" Text="Sign In / Out" CssClass="button small green"
                                                OnClick="lnkbtnFindStudent_Click"></asp:LinkButton>--%>
                                            <act:ModalPopupExtender ID="deleteModalPopupExtender" runat="server" CancelControlID="btnCancel"
                                                OkControlID="btnDelete" TargetControlID="lnkbtnFindStudent" PopupControlID="divDeleteConfirmation"
                                                BackgroundCssClass="modalBackground" />
                                            <act:ConfirmButtonExtender ID="deleteConfirmButtonExtender" runat="server" TargetControlID="lnkbtnFindStudent"
                                                Enabled="True" DisplayModalPopupID="deleteModalPopupExtender" />
                                        </asp:Panel>
                                        <asp:Panel ID="pnlAdjustReqHrs" CssClass="pnlButton" runat="server" Visible="false">
                                            <asp:Button ID="btnAdjustReqHrs" runat="server" Text="Adjust Required Hours" CssClass="button small green"
                                                OnClick="btnAdjustReqHrs_Click"></asp:Button>
                                        </asp:Panel>
                                    </div>
                                    <%--<asp:TextBox ID="TextBox1" type="text" runat="server" />--%>
                                    <%--<asp:Literal ID="ltReport" runat="server"></asp:Literal>--%>
                                    <div class="updateAlert">
                                        <asp:Panel runat="server" ID="pnlUpdateConfirmation" Visible="false" CssClass="UpdatedMessage Alert SavedSmall">
                                            <h3>
                                                <asp:Label runat="server" ID="lblConfirmationMsg" Text="Required hours updated."></asp:Label></h3>
                                        </asp:Panel>
                                        <asp:Panel runat="server" ID="pnlAllSignedOut" Visible="false" CssClass="UpdatedMessage Alert SavedSmall">
                                            <h3>
                                                <asp:Label runat="server" ID="lblAllSignedOut" Text="All students were signed out."></asp:Label></h3>
                                        </asp:Panel>
                                        <asp:Panel runat="server" ID="pnlStudyHallHoursMsg" Visible="false" CssClass="UpdatedMessage Alert SavedSmall">
                                            <h3>
                                                <asp:Label runat="server" ID="lblStudyHallHoursMsg" Text="Study hall hours are between 9AM - 9PM Mon-Thur 9AM - 4PM Fri and 6PM - 9PM Sun."></asp:Label></h3>
                                        </asp:Panel>
                                        <asp:Panel runat="server" ID="pnlSignedOutAllStudents" Visible="false" CssClass="UpdatedMessage Alert SavedSmall">
                                            <h3>
                                                <asp:Label runat="server" ID="lblSignedOutAllStudents" Text="Signed out all remaining signed in students."></asp:Label></h3>
                                        </asp:Panel>
                                        <asp:Panel runat="server" ID="pnlInvalidIp" Visible="false" CssClass="UpdatedMessage Alert SavedSmall">
                                            <h3>
                                                <asp:Label runat="server" ID="Label1" Text="This computer has not been designated for study hall."></asp:Label></h3>
                                        </asp:Panel>
                                    </div>
                                    <script type="text/javascript" src="http://api.jquery.com/scripts/events.js"></script>
                                    <%--<script type="text/javascript">
                                        var xTriggered = 0;
                                        var myLength = 0;
                                        var myString;
                                        var value;
                                        $("#txtStudentIdSearchBox").keyup(function (event) {
                                            myLength = $(this).val().length;
                                            if (myLength == 17) {
                                                value = $("#txtStudentIdSearchBox").val();
                                                value = value.substring(8);
                                                value = value.substring(0, value.length - 2);
                                                $("#txtStudentIdSearchBox").val(value);
                                            }
                                            if (event.which == 13) {
                                                event.preventDefault();
                                            }

                                            xTriggered++;
                                            var msg = "Handler for .keypress() called " + xTriggered + " time(s).";

                                            $.print(msg, "html");
                                            $.print(event);
                                        });

                                        $("#other").click(function () {
                                            $("#target").keypress();
                                        });
                                    </script>--%>
                                </fieldset>
                            </div>
                            <div style="float: left;">
                                <div class="filterControls" style="float: left; width: 340px;">
                                    <asp:Panel ID="pnlHow" runat="server">
                                        <div class="Contain" style="width: 185px;">
                                            <a id="aHow" runat="server" class="How">How does this page work?</a></div>
                                        <div class="HowTo" style="display: none;">
                                            <div class="InfoContainer">
                                                <div class="InfoContent">
                                                    <div id="div5" runat="server">
                                                        <h6 id="h1" runat="server">
                                                            View signed in students. Sign students in and out.</h6>
                                                        <p id="p1" runat="server">
                                                            Here you can see all the signed in student athletes, as well as sign them in and
                                                            out. Signing in and out can be done by:
                                                            <ol style="list-style: decimal">
                                                                <li>Entering a complete student ID</li>
                                                                <li><span>*</span>By doing a partial look up and then grabbing (copying and pasting)
                                                                    the desired student's ID into the 'Sign In / Out' box.</li>
                                                            </ol>
                                                            <br />
                                                            <br />
                                                            **If a partial look up is needed, a student can be looked up by partial first name,
                                                            last name or even partial student athlete ID. A list of matches will be returned
                                                            from which the desired student can be chosen and signed in.
                                                        </p>
                                                        <p id="p2" runat="server">
                                                            * Method typically used for finding student athletes that need to be signed in when
                                                            student ID is not available.<br />
                                                            ** May only be available for administrators of the system.
                                                        </p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </asp:Panel>
                                    <asp:Label ID="lblIPAddy" runat="server" Text=""></asp:Label>
                                </div>
                            </div>
                        </div>
                        <div class="lstNameLookUp">
                            <asp:Panel runat="server" ID="pnlAdminFilter" Visible="false">
                                <fieldset>
                                    <strong>Look up student by: </strong>
                                    <div id="Div1" class="rdBtnsAndSearch" runat="server" style="clear: none">
                                        <ul class="Three">
                                            <li>
                                                <asp:RadioButton ID="rbtnFirstName" runat="server" AutoPostBack="false" Checked="false"
                                                    GroupName="AddEdit" CssClass="Radio" Text="Student First Name" /></li>
                                            <li>
                                                <asp:RadioButton ID="rbtnLastName" runat="server" GroupName="AddEdit" CssClass="Radio"
                                                    Text="Student Last Name" Checked="false" AutoPostBack="false" /></li>
                                            <li>
                                                <asp:RadioButton ID="rbtnFullName" runat="server" GroupName="AddEdit" CssClass="Radio"
                                                    Text="Student Full Name" Checked="false" /></li>
                                        </ul>
                                        <asp:TextBox ID="tbxLookupName" type="text" class="studentIdInput1" runat="server" />
                                        <asp:Panel ID="pnlLookUpButton" CssClass="pnlButton" runat="server">
                                            <asp:LinkButton ID="lbtnLookUp" runat="server" Text="Look Up Student" CssClass="button small green"
                                                OnClick="lnkbtnFindStudent_Click"></asp:LinkButton>
                                        </asp:Panel>
                                    </div>
                                </fieldset>
                            </asp:Panel>
                        </div>
                        <strong>
                            <asp:Label runat="server" ID="lblCurrentWeek"></asp:Label></strong>
                    </div>
                </div>
            </div>
            <div>
                <sttc:StudentsSignedInGrid ID="MainGrid" runat="server" ResultType="1" ucAccessLevel='<%# Eval("Page.AccessLevel") %>' />
            </div>
            <div>
                <sttc:StudentsListGrid ID="StudentListGrid" runat="server" ResultType="1" ucAccessLevel='<%# Eval("Page.AccessLevel") %>' />
            </div>
            <asp:Panel runat="server" ID="pnlSignInOut">
                <div class="AddrdssBookContent UserProfile clearfix">
                    <div id="divDeleteConfirmation1" runat="server" align="center" class="confirmDelete"
                        style="display: none">
                        <div class="clearfix">
                            <div class="inner">
                                <h4>
                                    <asp:Label runat="server" ID="lblPasswordPrompt" Text=""></asp:Label></h4>
                                <asp:Label runat="server" ID="lblMonitorPassword" Text=""></asp:Label>
                                <asp:CheckBox runat="server" ID="cbxSignOutAll" Text="Sign Out All" />
                                <asp:TextBox ID="tbxMonitorPswrd" runat="server" TextMode="Password"></asp:TextBox>
                                <div class="notesProgram">
                                    <div class="signInOutNotes">
                                        <h4>
                                            <asp:Label runat="server" ID="lblNotes" Text="Notes: "></asp:Label></h4>
                                        <asp:TextBox ID="tbxNotes" runat="server" TextMode="MultiLine" Rows="3" Width="300"></asp:TextBox>
                                    </div>
                                    <div class="programAttended">
                                        <h4>
                                            <asp:Label runat="server" ID="lblPrgrmAttnd" Text="Program Attended: "></asp:Label></h4>
                                        <asp:TextBox ID="tbxPrgrmAttnd" runat="server" TextMode="MultiLine" Rows="3" Width="300"></asp:TextBox>
                                    </div>
                                </div>
                                <div class="Buttons">
                                    <ul style="display: none;">
                                        <li>
                                            <asp:RadioButton ID="rbtnLockPassword" runat="server" AutoPostBack="false" Checked="false"
                                                GroupName="LockUnlockPassword" CssClass="Radio" Text="Lock password" /></li>
                                        <li>
                                            <asp:RadioButton ID="rbtnUnlockPassword" runat="server" GroupName="LockUnlockPassword"
                                                CssClass="Radio" Text="Unlock password" Checked="false" /></li>
                                    </ul>
                                    <asp:Button ID="btnSignIn" CssClass="button small" runat="server" Text="Sign In / Out"
                                        OnClick="btnSignIn_click" Style="margin-left: 15px;" />
                                    <asp:Button ID="btnCancel" CssClass="button small" runat="server" Text="Cancel" />
                                </div>
                                <asp:Label runat="server" ID="lblInvalidPassword" Visible="false"></asp:Label>
                            </div>
                        </div>
                    </div>                    
                </div>
            </asp:Panel>
            <asp:Panel runat="server" ID="Panel1">
                <div class="AddrdssBookContent UserProfile clearfix">
                    <div id="divWeekTimeTotal" runat="server" align="center" class="confirmDelete" style="display: none">
                        <div class="clearfix">
                            <div class="inner">
                                <div class="notesProgram">
                                    <div class="signInOutNotes">
                                        <h4>
                                            <asp:Label runat="server" ID="lblCurrentWeekTotal" Text="Current Week Total "></asp:Label></h4>
                                        <asp:TextBox ID="txbCurrentWeekTotal" runat="server" TextMode="MultiLine" Rows="1"
                                            Width="300" Font-Size="Large" Font-Bold="true"></asp:TextBox>
                                        <asp:LinkButton ID="LinkButton1" CssClass="button small" runat="server" Text="Close"
                                            Visible="false" />
                                        <act:ModalPopupExtender ID="deleteModalPopupExtender1" runat="server" CancelControlID="btnCancel"
                                            OkControlID="btnDelete" TargetControlID="LinkButton1" PopupControlID="divWeekTimeTotal"
                                            BackgroundCssClass="modalBackground" />
                                        <act:ConfirmButtonExtender ID="deleteConfirmButtonExtender1" runat="server" TargetControlID="LinkButton1"
                                            Enabled="True" DisplayModalPopupID="deleteModalPopupExtender1" />
                                    </div>
                                </div>
                                <div class="Buttons">
                                    <asp:LinkButton ID="lnkbtnClose" CssClass="button small" runat="server" Text="Close"
                                        OnClick="lnkbtnClose_OnClick" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </asp:Panel>
        </div>
    </div>
</asp:Content>

Open in new window

0
 
guru_samiCommented:
Yes it is and should be inside it:

<script type="text/javascript">
         $(function () {
            $(".txt3").keypress(function (e) {
                if (e.keyCode == 13) {
                    e.preventDefault();
                }
            });
        });
</script>

Open in new window

0
 
Michael SterlingWeb Applications DeveloperAuthor Commented:
I put this in place and it worked. Thanks!
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now