Make button respond to the Enter Key

你说的曾经没有我的故事 提交于 2021-01-29 18:36:10

问题


I have a button on my form, and when the button is clicked, it takes the value of a textbox and populates that value into a list. Usually, when someone hits the enter key on a form, then the form is submitted but I have written this to stop that behavior:

$(document).on("keypress",
    "form",
    function(event) {
        return event.keyCode != 13;
    });

But, now I would like the functionality of the Enter key to be used for the purpose of the button on the form. As of now I have this code (based on the click) for it's current functionality:

$("#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'>&times;</button></li>");
    $("#Weigh-Location-Count-ListBox").append("<option data-uid='" +
        uid +
        "' selected='true' value='" +
        myVal +
        "'>" +
        myVal +
        "</option>");
    $("#WL-TxtBox").val("");
});

How do I make that button respond to both click and the enter key?


回答1:


  1. Make the button a submit
  2. Put it inside a form along with the text box
  3. Handle the forms submit event instead of the buttons click event
  4. Inside your keypress handler, check the target of the event. If it's the textbox you care about, let the enter go through.

Sample

<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'>&times;</button></li>");
$("#Weigh-Location-Count-ListBox").append("<option data-uid='" +
    uid +
    "' selected='true' value='" +
    myVal +
    "'>" +
    myVal +
    "</option>");
$("#WL-TxtBox").val("");

e.preventDefault();
});



回答2:


Make a function that will be called from both the click and the enter key, lets say you called it action().

Then when the button is pressed, do:

if (event.keyCode === 13) {
    action()
}

And replace the

$("#WL-Add-Btn").click(function () {....

With

$("#WL-Add-Btn").click(action)


来源:https://stackoverflow.com/questions/52211240/make-button-respond-to-the-enter-key

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