Blazor preventDefault on submit form

别说谁变了你拦得住时间么 提交于 2020-07-10 02:52:24

问题


Inside my EditForm, I want to prevent that the user submits the form by pressing the Enter key.

I have tried the following, but didn't work.

<button type="submit" @onkeypress:preventDefault>Save</button>

Many thanks!


回答1:


I have got this working by just putting 2 submit button's in the EditForm, with the first one disabled.

<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<button type="submit">Save</button>



回答2:


Here's a working code sample, run it and see for yourself that the form is not submitted when you hit the Enter key:

Enter a value into the first field, then second field, then tab out, and hit Enter. Now look what is printed in the Output window... Do you see the "Submit..." string ? I think not.

<h1>My articles</h1>

<p>Leave me a comment</p>
<p>Note that the Save button is located outside of the EditForm component.</p>
<EditForm  Model="Model" OnValidSubmit="HandleValidSubmit">
    <DataAnnotationsValidator />

    <div class="form-group">
        <label for="name">Name: </label>
        <InputText Id="name" Class="form-control" @bind-Value="@Model.Name"> 
                                                             </InputText>
        <ValidationMessage For="@(() => Model.Name)" />

    </div>
    <div class="form-group">
        <label for="body">Text: </label>
        <InputTextArea Id="body" Class="form-control" @bind- 
                                         Value="@Model.Text"></InputTextArea>
        <ValidationMessage For="@(() => Model.Text)" />
    </div>
    <p>
        <button type="submit" @onkeypress="@KeyHandler" 
                              @onkeypress:preventDefault>Submit</button>
    </p>
</EditForm>


@code
{

    private Comment Model = new Comment();

    private void HandleValidSubmit()
    {
        Console.WriteLine("Submit...");
    }

    void KeyHandler(KeyboardEventArgs args)
    {
        if (args.Key == "Enter")
        {
           return;
        }
        Console.WriteLine("KeyHandler...");

    }

}



回答3:


Try this:

  <button type="submit" @onkeypress="@KeyHandler" 
                                  @onkeypress:preventDefault>Submit</button>

And this:

    void KeyHandler(KeyboardEventArgs args)
    {
        if (args.Key == "Enter")
        {
            return;
        }


    }



回答4:


Here is an answer for JavaScript, it's also a plea not to do it: The Enter Key should Submit Forms, Stop Suppressing it

If you still want to do this: make sure your form has more than one input and no submit button.

 <button type="button" @onclick="MySubmit">Save</button>

and then handle your validation in MySubmit, using an EditContext or whatever.



来源:https://stackoverflow.com/questions/61167239/blazor-preventdefault-on-submit-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!