-1

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?

robni
  • 904
  • 2
  • 6
  • 20
  • Please provide a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) which illustrates what you're describing. If applicable, adding images to your post may also be beneficial. – Tu deschizi eu inchid Jun 22 '22 at 16:32
  • The code provided above simply will not work. runat="server" items must be declared in the aspx page or like this: Dim TextBox1 As TextBox = New TextBox TextBox1.Id="TextBox1" Page.Controls.Add(TextBox1) However, you cannot add forms like this. It will cause you a real headache. You can only have one runat="server" form on a .NET page. – Fawlty Jun 23 '22 at 08:17

3 Answers3

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.

Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51
  • I think I understand how I could do that, but how could I change the defaultbutton to be either one of those buttons? From my understanding, what you are describing would still result in me having to physically click the button before any procedure is ran, how would I make the enter button run the procedure? I know I could get rid of one button and have there just be one calculate button that would determine which textbox is empty and run the proper procedure based off that, but to prevent confusion, I need there to be two buttons – amelia zaripova Jun 22 '22 at 16:33
  • You can have the two buttons. But, just keep in mind that if they enter text and hit enter key, the FIRST button that follows the text box will be clicked. but, I fail to see why having two buttons would be issue? Those two buttons can run the one click event, or each button can have their own click event. But, both of those buttons can freely check the values of text boxes and take the action you want. So, I see no problem with two buttons - they each can check values of text boxes. but, do keep in mind the above rule - the button that follows the text box gets clicked on when they hit enter – Albert D. Kallal Jun 22 '22 at 16:40
  • So you can start messing around with javascript, but I don't think that road is required. I mean, what information are you going to use that runs the default button? Since that information comes from the form, then have both buttons check the text box values or do whatever based on what your criteria was in the first place to "change" the default behavior. Perhaps you might consider hiding one button based on inputs, and that could well reduce confusing here, but those buttons are free to test/check the data entered and do whatever you want anyway. So, some extra logic for 2 buttons. – Albert D. Kallal Jun 22 '22 at 16:43
  • ah, so you're saying have each button run the same procedure, just check which text box is empty first? I am essentially creating a calculator to calculate membrane pressure or diamond pressure with multiple inputs including membrane pressure, diamond pressure, diameters, etc. The only issue I see with this is that if the calculate membrane pressure button is clicked and diamond pressure field is empty, I have coded an error message to return and say that there is a missing input. If I do it this way though, wouldn't that error message now not pop up and it would just calculate the other one? – amelia zaripova Jun 22 '22 at 16:46
  • also, you say that the button following the text box is the one that is clicked? I am finding that the first button I created is always the one clicked, no matter which textbox has the focus. – amelia zaripova Jun 22 '22 at 16:49
  • You are correct - my apologies - the FIRST button on the page is clicked on when you hit enter key - my sorry, my bad. You have to set the button visible = false for that button to NOT click. Even hiding it with style will not work. You can also go Button1.Enabled = false. – Albert D. Kallal Jun 22 '22 at 17:29
  • HOWEVER, you can turn this feature off by setting UseSubmitBehavior="False" in the markup. Now, the buttons can be freely clicked on, but hitting enter key will NOT trigger those (that first) button on the page. This suggests that you could set the text box to autopost back = true, and use the text changed event of the text box if you want code behind to trigger and fire when user hits enter or even tab key. So, use text box text changed event for this - have that code do the same thing as a button that follows the text box. – Albert D. Kallal Jun 22 '22 at 17:33
0

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?

robni
  • 904
  • 2
  • 6
  • 20
0

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>
Fawlty
  • 451
  • 2
  • 9
  • sorry if this is a stupid question, I am very new to this, would I just replace every instance of $ with windows.jquery and every instance of this with the appropriate button name? I'm confused how I should change this code to actually run – amelia zaripova Jun 22 '22 at 17:56
  • This code will run as-is. I have added lots of comments for you. I suggest copying and pasting it in and trying it. Press F12 on your browser, then go to the script tab, then put breakpoints on the javascript to see how it works. I will edit my answer now to try to give more details. You will only learn by experimenting. – Fawlty Jun 23 '22 at 08:03