Use Enter key press for focus change and check input before submit form

AKM Azad 20 Reputation points
2024-09-17T05:42:40.7266667+00:00

I have a asp.net form content dropdownlist, textbox and button. I want to implement Enter key press to change focus and check input before submit form. I use onkeyup="EnterPressFocusChange(this, event)" for change focus and OnClientClick="return CheckInputData(this);" for check input data before submit. When I use button property UseSubmitBehavior="false" then change focus task working but checking input function always return true and button onCkick function calls. And when I use button property UseSubmitBehavior="true" then onCkick function calls when I press Enter Key press . How can I complete both task? Below the code that I try.

<script type="text/javascript">
        function CheckInputData(a) { 
            // If valid input return true
            // else return false
        }
        function EnterPressFocusChange(a, event) {
            if (event.which == 13) {
                // Change focus
            }
        }
    </script>

    <form runat="server">
        <asp:DropDownList ID="DropDownList1" runat="server" onkeyup="EnterPressFocusChange(this, event)" AutoPostBack="true"></asp:DropDownList>
        <asp:TextBox ID="tb1" Text="0" runat="server" onkeyup="EnterPressFocusChange(this, event)"></asp:TextBox><br />
        <asp:Button ID="btnButton" runat="server" Text="Button" OnClientClick="return CheckInputData(this);" UseSubmitBehavior="false" OnClick="btnButton_Click"/>
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,459 questions
0 comments No comments
{count} votes

Accepted answer
  1. XuDong Peng-MSFT 10,511 Reputation points Microsoft Vendor
    2024-09-17T08:25:04.34+00:00

    Hi @AKM Azad,

    How can I complete both task?

    First prevent the enter key from submitting the form.

    Secondly, you set the EnterPressFocusChange event for both the DropDownList and TextBox elements. Then you need to determine the event source element and perform the corresponding operation.

    Third, since the OnClientClick event is executed before OnClick event, you can return true/false to determine whether to allow the form to be submitted. Therefore, you do not need to set the UseSubmitBehavior property in submit button.

    Here is a simple test:

    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-3.4.1.min.js" ></script>
        <script type="text/javascript">
            //prevent submit from Enter key
            $(document).ready(function () {
                $(window).keydown(function (event) {
                    if (event.keyCode == 13) {
                        event.preventDefault();
                        return false;
                    }
                });
            });
            function CheckInputData() {
                // If valid input return true
                // else return false
    			// As a simple example, determine whether the TextBox value contains "test"
                var text = document.getElementById("tb1").value;
                if (text.includes("test")) {
                    console.log("Valid Input");
                    return true;
                } else {
                    console.log("Invalid Input");
                    return false;
                }
            }
            function EnterPressFocusChange(event) {
                if (event.key === "Enter" || event.keyCode === 13) {
                    // Determine which element is the source of the event
                    if (event.target.id === "DropDownList1") {
                        // Do something here, print its value on the console as an example
                        const dropdown = document.getElementById("DropDownList1");
                        const selectedOption = dropdown.options[dropdown.selectedIndex].text;
                        console.log("Dropdown selected: " + selectedOption);
                        // change focus here, move focus from dropdownlist to textbox
                        document.getElementById("tb1").focus();
                    } else if (event.target.id === "tb1") {
                        // Do something here, print its value on the console as an example
                        const textboxValue = event.target.value;
                        console.log("Textbox input: " + textboxValue);
                        // change focus here, move focus from textbox to button
                        document.getElementById("btnButton").focus();
                    }
                }
            }
        </script>
    </head>
    <body>
    <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="DropDownList1" runat="server" onkeyup="EnterPressFocusChange(event)" AutoPostBack="true">
                <asp:ListItem Value="1" Text="Item1">Item1</asp:ListItem>
                <asp:ListItem Value="2" Text="Item2">Item2</asp:ListItem>
                <asp:ListItem Value="3" Text="Item3">Item3</asp:ListItem>
            </asp:DropDownList>
            <br />
            <asp:TextBox ID="tb1" Text="0" runat="server" onkeyup="EnterPressFocusChange(event)"></asp:TextBox><br />
            <asp:Button ID="btnButton" runat="server" Text="Button" OnClientClick="return CheckInputData(this);" OnClick="btnButton_Click"/>
        </div>
    </form>
    </body>
    

    Result:

    User's image

    Best regards,

    Xudong Peng


    If the answer is the right solution, please click "Accept Answer" and kindly upvote. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. SurferOnWww 2,661 Reputation points
    2024-09-17T06:49:51.86+00:00

    First, please consider using the Tab key (not the Enter key) to change the focus because the Enter key will submit the form when the focus is on the textbox. It might cause unexpected result.

    Second, please consider using the validator controls such as the RequiredFieldValidator, RegularExpressionValidator and CustomValidator for the validation of user inputs.

    Sample

    <%@ Page Language="C#" AutoEventWireup="true" 
        CodeBehind="WebForm42.aspx.cs" 
        Inherits="WebForms1.WebForm42" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script type="text/javascript">
            function DropDwonListValidate(sender, args) {
                var ddl =
                    document.getElementById('<%= DropDownList1.ClientID%>');
    
                if (ddl.value == "2") {
                    args.IsValid = false;
                } else {
                    args.IsValid = true;
                }
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:DropDownList 
                ID="DropDownList1" 
                runat="server" >
                <asp:ListItem Text="AAA" Value="1" Selected="True" />
                <asp:ListItem Text="BBB" Value="2" />
                <asp:ListItem Text="CCC" Value="3" />
            </asp:DropDownList>
            <asp:CustomValidator ID="CustomValidator1"
                runat="server"
                ForeColor="Red"
                Display="Dynamic"
                ErrorMessage="do not select bbb"
                ClientValidationFunction="DropDwonListValidate"
                ControlToValidate="DropDownList1">
                    </asp:CustomValidator>
            <br />
            <asp:TextBox ID="tb1" 
                runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator 
                ID="RequiredFieldValidator1"
                runat="server"
                ErrorMessage="input rquired"
                ControlToValidate="tb1"
                ForeColor="Red"
                Display="Dynamic">
            </asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator 
                ID="RegularExpressionValidator1"
                runat="server"
                ErrorMessage="must be less than 5 characters"
                ControlToValidate="tb1"
                ForeColor="Red"
                ValidationExpression="^[0-9a-zA-Z]{1,5}$"
                Display="Dynamic">
            </asp:RegularExpressionValidator>
            <br />
            <asp:Button 
                ID="btnButton" 
                runat="server" 
                Text="Button"             
                OnClick="btnButton_Click"/>
        </form>
    </body>
    </html>
    

    Result

    enter image description here


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.