我在表单上有一个按钮,单击该按钮时,它将获取文本框的值并将该值填充到列表中。通常,当有人按下表单上的Enter键时,便会提交表单,但我已编写此命令来停止该行为:
$(document).on("keypress",
"form",
function(event) {
return event.keyCode != 13;
});
但是,现在我希望将Enter键的功能用于表单上的按钮。截至目前,我已经获得了此代码(基于点击),以了解其当前功能:
$("#WL-Add-Btn").click(function () {
var myVal = $("#WL-TxtBox").val();
console.log(myVal);
var uid = generateId();
$("#Weight-Location-Count-List")
.append("<li data-uid='" + uid + "' data-id='" +
myVal +
"' class='list-group-item list-group-item-default text-info mb-1' >" +
myVal +
" <button type='button' class='close remove-button'>×</button></li>");
$("#Weigh-Location-Count-ListBox").append("<option data-uid='" +
uid +
"' selected='true' value='" +
myVal +
"'>" +
myVal +
"</option>");
$("#WL-TxtBox").val("");
});
我如何使该按钮同时响应单击和Enter键?
答案 0 :(得分:3)
submit
form
内样品
<form id="frm">
<textarea id="WL-TxtBox"></textarea>
<button type="submit" id="WL-Add-Btn">Button</button>
</form>
$(document).on("keypress",
"form",
function(event) {
return !$(event.target).is($("#WL-TxtBox")) && event.keyCode != 13;
});
$("#frm").submit(function (e) {
var myVal = $("#WL-TxtBox").val();
console.log(myVal);
var uid = generateId();
$("#Weight-Location-Count-List")
.append("<li data-uid='" + uid + "' data-id='" +
myVal +
"' class='list-group-item list-group-item-default text-info mb-1' >" +
myVal +
" <button type='button' class='close remove-button'>×</button></li>");
$("#Weigh-Location-Count-ListBox").append("<option data-uid='" +
uid +
"' selected='true' value='" +
myVal +
"'>" +
myVal +
"</option>");
$("#WL-TxtBox").val("");
e.preventDefault();
});
答案 1 :(得分:0)
制作一个既可以通过单击又可以按Enter键调用的函数,可以说您将其称为action()。
然后在按下按钮时执行:
if (event.keyCode === 13) {
action()
}
然后替换
$("#WL-Add-Btn").click(function () {....
使用
$("#WL-Add-Btn").click(action)