【发布时间】:2020-04-12 05:28:21
【问题描述】:
在我的EditForm 中,我想防止用户通过按Enter 键来提交表单。
我尝试了以下方法,但没有成功。
<button type="submit" @onkeypress:preventDefault>Save</button>
非常感谢!
【问题讨论】:
-
您的意思是当光标在文本字段中然后按“输入”时您不想提交?如果提交按钮有焦点,然后按“回车”,那么你要提交吗?
在我的EditForm 中,我想防止用户通过按Enter 键来提交表单。
我尝试了以下方法,但没有成功。
<button type="submit" @onkeypress:preventDefault>Save</button>
非常感谢!
【问题讨论】:
我只需将 2 个提交按钮放在 EditForm 中即可完成这项工作,第一个按钮被禁用。
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<button type="submit">Save</button>
【讨论】:
这里是 JavaScript 的答案,也请不要这样做:The Enter Key should Submit Forms, Stop Suppressing it
如果你仍然想这样做:确保你的表单有多个输入和没有提交按钮。
<button type="button" @onclick="MySubmit">Save</button>
然后使用 EditContext 或其他方法在 MySubmit 中处理您的验证。
【讨论】:
这是一个工作代码示例,运行它并亲自查看当您按下 Enter 键时表单没有提交:
在第一个字段中输入一个值,然后在第二个字段中输入一个值,然后按 Tab 键,然后按 Enter。现在看看输出窗口中打印的内容......你看到“提交......”字符串吗?我想不是。
<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...");
}
}
【讨论】:
试试这个:
<button type="submit" @onkeypress="@KeyHandler"
@onkeypress:preventDefault>Submit</button>
还有这个:
void KeyHandler(KeyboardEventArgs args)
{
if (args.Key == "Enter")
{
return;
}
}
【讨论】: