Skip to content Skip to sidebar Skip to footer

Make Button Respond To The Enter Key

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 for

Solution 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">
    <textareaid="WL-TxtBox"></textarea><buttontype="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();
});

Solution 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)

Post a Comment for "Make Button Respond To The Enter Key"