0

I have a jquery function:

$("#get-input").keyup(function (event) {
    if (event.keyCode === 13) {
        $("#get-data").click();
    }
});

$("#get-data").click(function (e) {
    var endpoint = $(".get-input").val();

    if ($('#data-display').is('[hidden]')) {
        $('#data-display').removeAttr('hidden');
    }

    $.ajax
        ({
            url: "https://localhost:44398/api/" + endpoint,
            type: 'get',
            success: function (data) {
                $('.formatted-json').text(JSON.stringify(data, null, '\t'))
            }
        });
});

My form:

<form class="form-inline">
                <div class="form-group query-container">
                    <label class="get-lbl pr-2">this is the label</label>
                    <input type="text" class="form-control-lg get-input" placeholder="placeholder" />
                    <input type="button" class="btn btn-orange btn-get" id="get-data" value="submit" />
                </div>
            </form>

This works perfectly when I click the #get-data button. The ajax is hit, and the data is displayed. My issue is that when I hit the enter key, it reloads the entire page. I need the enter key to act the same as if I clicked the button.

I have tried changing the keyup to keydown and keypress without luck. I have tried changing the .click function to a .submit function on the form instead of the input. I have also wrapped all the JS inside a document ready call, but it still works the same.

Does anyone have any ideas what I need to do to get this working properly when I press enter?

dotnetdev
  • 61
  • 3
  • 8
  • 1
    https://www.w3schools.com/jquery/event_preventdefault.asp and check existing answers: https://stackoverflow.com/questions/37450508 – Akber Iqbal Jun 13 '20 at 03:58
  • Thanks for that, unfortunately I have tried both of those suggestions, but the page still reloads on enter. – dotnetdev Jun 13 '20 at 04:19
  • Check out https://stackoverflow.com/questions/699065/submitting-a-form-on-enter-with-jquery – Kunal mathur Jun 13 '20 at 04:39
  • Thanks for that link. I tried all the suggestions there, but this form still reloads the page when I press enter. – dotnetdev Jun 14 '20 at 02:51
  • Does this answer your question? [Prevent bootstrap form to submit with "Enter"](https://stackoverflow.com/questions/59503468/prevent-bootstrap-form-to-submit-with-enter) – Michael Freidgeim Jul 12 '23 at 21:04

1 Answers1

0

This is not quite an answer, but it's the best I could come up with. If someone has a better solution, I will happily mark it as the answer instead of this!

I ended up adding onsubmit="return false" to my opening form tag.

This ensured that the user could not press enter to submit the form. So the user can now only submit the form by clicking on the button which will trigger the jQuery click function.

dotnetdev
  • 61
  • 3
  • 8