Search code examples
blazorkeypress.net-5preventdefaultblazor-editform

How to Disable ENTER Key Press for submit button when using Blazor <InputText>


I can't seem to find a way how to disable the enter key in a <button type="submit"> wrapped inside an <EditForm>.

The problem is that at any blazor <InputText> control, when a user presses the ENTER key, blazor activates the validation and submit process.

I also tried using <button type="submit" @onkeypress="@KeyHandler" @onkeypress:preventdefault> but it does not work, the form still proceeds to validate and submits.

More specifically inside my <EditForm> I am calling a modal dialog that contains an <InputText> for searching items, and every time ENTER is pressed to perform the search, the form gets validated and submitted in the background :(

Please help 🙏🙏🙏


Solution

  • Try the following:

    <InputText @bind-Value="_model.Value" onkeypress="return event.keyCode!=13"/>
    <input @bind-value="_model.Value" onkeypress="return event.keyCode!=13" />
    

    credit to @dustysilicon.

    Here's my Test Page:

    @page "/Editor"
    <h3>EditForm</h3>
    
    <EditForm EditContext="this._editContext" OnSubmit="SubmitForm">
        <div class="p-2">
            No Enter: <InputText @bind-Value="_model.SelectValue" onkeypress="return event.keyCode!=13"></InputText>
        </div>
        <div class="p-2">
            No Enter: <input type="number" @bind-value="_model.Value" onkeypress="return event.keyCode!=13" />
        </div>
        <div class="p-2">
            Enter: <input @bind-value="_model.SelectValue" />
        </div>
        <div class="p-2">
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
    </EditForm>
    <div class="m-2 p-2">Value: @_model.Value</div>
    <div class="m-2 p-2">@message</div>
    
    @code {
    
        public class Model
        {
            public int Value { get; set; }
            public string SelectValue { get; set; }
        }
    
        private string message;
        Model _model = new Model();
    
        EditContext _editContext;
    
        protected override void OnInitialized()
        {
            _editContext = new EditContext(_model);
        }
    
        void SubmitForm()
        {
            message = $"Form Submitted at :{DateTime.Now.ToLongTimeString()}";
        }
    }