skip to Main Content

I have a web form in asp.net coding with vb and it has multiple textboxes and buttons. If one textbox is empty, I would like one button to be clicked if the enter key is pressed, whereas if a different textbox is empty, I would like the other button to be clicked, when the enter key is pressed. I know I can change the default button in the form section, but I don’t know how I could go about changing the default button depending on which textbox is empty? I assume I have to do this in javascript, which I have little understanding of so any help would be much appreciated.

Can I do something like this to change the default button?

If txtMembranePressure.Text = "" Then
    Dim sb As New System.Text.StringBuilder()
    sb.Append("<form id='form1' runat='server'" + "defaultbutton='btnMembranePressure'")
Else
    Dim sb As New System.Text.StringBuilder()
    sb.Append("<form id='form1' runat='server'" + "defaultbutton='btnDiamondPressure'")
End If

Could I put the default button directly on the form like this?

3

Answers


  1. There are 3 steps to do.

    1. You need to know, when a Textbox is changed. For that you can use the TexboxChanged Event.
    2. You need to know, if the Textbox is empty.
    3. You need to know, how to change the default button.

    Every Textbox need a TextboxChanged Event. And in every event you should check, if the Textbox is empty. If it is empty, you should set it to default.

    In Pseudocode:

    if Textbox.Text = "" then
    set Textbox to default
    

    For further information on the Textbox Change EVent, search in a searchengine (for example duckduckgo.com) for "textbox changed event":

    https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/

    To change the default button, please consider following Answers at Stackoverflow:
    How to set the default button for a TextBox in ASP.Net?

    Login or Signup to reply.
  2. Would it not be better to have one click routine – all buttons can freely point to that one click routine – but inside of that click routine, you can freely check the value(s) of the given text boxes, and then run the desired code. This seems a whole lot less complex then trying to change what actual button supposed to be clicked. So, have all buttons run the SAME routine, but that routine can simple check which text boxes have values in them.

    Then based on what text boxes have (or have not) a value, you simple run or call the code you want based on this information.

    Keep in mind, that in most cases, hitting enter key will trigger the button that FOLLOWS the control in the markup after that text box.
    Edit: correction: the FIRST button on the page will trigger.

    However, you can TURN OFF this behavour by setting in the button markup usesubmitBehaviour=False

    <asp:TextBox ID="txtSearchOC" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button"
        UseSubmitBehavior="False" />
    

    In fact, if you drop a text box on a form, then say a gridview with 10 rows, and each row of the gridviewe has button with click event? Hitting enter key in above will in fact trigger the FIRST row button click of the gridview!!!

    So, often by correct placement of buttons, say like a search text box, and a button after to click "search data", then in fact, if they hit enter key, the button that follows that text box will trigger anyway. (as noted, first button on markup fires – not any button, or not actually the one that follows the textbox).

    So, in some cases, the correct order of a text box, and the button that follows can be put to good use here. But, often it can surprise you. You drop in a text box, and a form has 10 buttons that follow, ONE of them WILL trigger when you hit enter key – and this can often be harder to PREVENT this from occurring.

    So, keep the above in mind. but, given that you want code to run based on values in text boxes (or lack of values), then I would have ONE routine that the button clicks ALL use, and the code behind can then check the text box values, and take the desired course of action and run your desired code based on this information.

    Login or Signup to reply.
  3. I have provided you with sufficient detail and example code below to re-engineer this yourself, even if I have not quite understood your requirement. I do agree with the comments above, this is probably not the best approach. You are better off checking server-side whether text boxes are populated or not, and then following a different path in your code.

    JQuery lets you find elements by class name (CssClass="" in .NET, class="" on a normal HTML element)

    $(".ClassName") makes JQuery find all elements with that class name on the page.
    $("#Id") makes JQuery find all elements with that Id on the page.

    data-whatYouWantToStore is a convenient way of storing data against an element, that you can then read with Javascript / JQuery. Just keep it all lower case to avoid upsetting it.

    $(element).data("the name after the data- bit") will get you the value.

    The only bits you need to change to make it run are on the text-boxes:

    data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"
    

    Set the class of the button you want it to click when enter is pressed, if the textbox is empty in the data-targetbuttonemptyclass property, and the button to click if text is present in the data-targetbuttonnotemptyclass property. Text boxes must have the class js-click-if-not-empty set on them if you want them to be handled by the "empty / not empty" JavasScript.

    <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Buttons.aspx.vb" Inherits="Scrap.Buttons" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <!--Add reference to Jquery CDN -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <!--Your Javascript -->
        <script type="text/javascript">
            $(document).ready(function () {
                // find all the buttons we want to set this behaviour on
                $(".js-click-if-not-empty").each(function () {
                    // add a keypress event hander to each button
                    $(this).on("keypress", function () {
                        // get the key that was pressed
                        var keycode = (event.keyCode ? event.keyCode : event.which);
                        // is it the ENTER key?
                        if (keycode === 13) {
                            // prevent anything else that was going to happen because enter was pressed.
                            event.preventDefault();
                            // is the textbox empty?
                            if ($(this).val() === "") {
                                // yes - get the css class of the button to click when the textbox is empty 
                                var button = $("." + $(this).data("targetbuttonemptyclass"))[0];
                                // just for debugging to show which button is about to be clicked
                                alert("going to click empty button: " + button.id);
                                // click the button
                                button.click();
                            } else {
                                // no - get the css class of the button to click when the textbox is not empty
                                var button = $("." + $(this).data("targetbuttonnotemptyclass"))[0];
                                // just for debugging to show which button is about to be clicked
                                alert("going to click not empty button: " + button.id);
                                // click the button
                                button.click();
                            }
                        };
                    });
                });
            });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:TextBox ID="tb_TextBox1" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
                <asp:TextBox ID="tb_TextBox2" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
                <asp:TextBox ID="tb_TextBox3" runat="server" CssClass="js-click-if-not-empty" data-targetbuttonemptyclass="js-button-1" data-targetbuttonnotemptyclass="js-button-2"></asp:TextBox>
                <asp:Button ID="btn_ClickIfEmpty" runat="server" CssClass="js-button-1" Text="Click If Empty" />
                <asp:Button ID="btn_ClickIfNotEmpty" runat="server" CssClass="js-button-2" Text="Click If Not Empty" />
            </div>
        </form>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search