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:
- Make the button a
submit
- Put it inside a
form
along with the text box - Handle the forms submit event instead of the buttons click event
- 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'>×</button></li>");
$("#Weigh-Location-Count-ListBox").append("<option data-uid='" +
uid +
"' selected='true' value='" +
myVal +
"'>" +
myVal +
"</option>");
$("#WL-TxtBox").val("");
e.preventDefault();
});
Post a Comment for "Make Button Respond To The Enter Key"