var input = document.getElementById("myInput");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});
document.getElementById("pw")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function buttonCode()
{
alert("Button code executed.");
}
### please check the source for in detail explanation ###
In jQuery, the following would work:
$("#id_of_textbox").keyup(function(event) {
if (event.keyCode === 13) {
$("#id_of_button").click();
}
});
$("#pw").keyup(function(event) {
if (event.keyCode === 13) {
$("#myButton").click();
}
});
$("#myButton").click(function() {
alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton">Submit</button>
Or in plain JavaScript, the following would work:
document.getElementById("id_of_textbox")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("id_of_button").click();
}
});
document.getElementById("pw")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function buttonCode()
{
alert("Button code executed.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button>