Reputation: 5953
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'>×</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?
Upvotes: 0
Views: 705
Reputation: 149
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)
Upvotes: 0
Reputation: 8815
submit
form
along with the text boxSample
<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();
});
Upvotes: 4