如何捕获Html.TextBoxFor上的Enter键并调用jQuery函数

时间:2019-06-17 20:46:02

标签: c# jquery asp.net-mvc

当用户按下Enter键时,我想向HTMLhelper文本框上的函数触发事件。以下代码块不起作用。我在这里做什么错了?

@Html.LabelFor(model => model.Search.EmployeeID)
@Html.TextBoxFor(model => model.Search.EmployeeID, new { @class = "form-control", @id = "customEmployeeID", @onkeypress = "keypresshandle(event);" })

function keypresshandle(e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        alert("Enter was pressed was presses");
    }
}

3 个答案:

答案 0 :(得分:0)

这是@Html.TextBoxFor呈现控件的方式,例如:

剃刀视图:

@model Student
@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })   

HTML结果:

<input class="form-control" 
        id="StudentName" 
        name="StudentName" 
        type="text" 
        value="John" />

我建议您通过Html Helpers来加强其工作原理的认识。

只要输入控制标签的name="propName"与模态对象属性匹配,控制器的obj参数将接收其值。如果您在使用@Html.TextBoxFor生成控件时遇到问题,请使用图例的方法:

function someFunction(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    alert("omg you pressed the Enter key. How dare you!");
  }
}
<input type="text" name="StudentName" id="StudentName" onkeypress="someFunction(event);" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

答案 1 :(得分:0)

@ *使用htmlAttributes关键字* @

@Html.EditorFor(model => model.Search.EmployeeID, new { htmlAttributes = new { @class = "form-control", @onkeypress = "keypresshandle(event);" } })

@ *请在此处放置脚本标签* @

<script>
    function keypresshandle(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            alert("Enter was pressed was pressed");
        }
    }
</script>

答案 2 :(得分:0)

就我而言,onkeypress 事件不起作用。 onkeydown 有效。代码如下:

<input id="myHostName" autocomplete="on" class="txtHostname" type="text" onkeydown="ThisIsEnter(event);" />

<input name="SubmitButton" id="Submitbtn" type="submit" value="SearchHostAttributes" class="myButton" />

<script>
function ThisIsEnter(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            document.getElementById("Submitbtn").click();
        }
    }
</script>