Reputation: 363
I have an input it has a function running if the keycode ==13
I also have a button on the same page if the user clicks that button it should trigger click event associated with it and at the same time it should also fire the enter click using javascript
the code is shown as below
<input type="text" class="myInputValue">
<button class="myLink">submit</button>
(function(){
var inputc = document.getElementsByClassName('myInputValue')[0];
var submitbtn = document.getElementsByClassName('myLink')[0]
inputc.addEventListener("keydown", function(e){
if(e.keyCode == 13){
alert("Entered")
}
});
submitbtn.addEventListener("click", function(e){
// here I need functionality which will fire enter key event too
});
})();
Upvotes: 0
Views: 1476
Reputation: 1086
Instead you can call the btn event on enter.
(function(){
var inputc = document.getElementsByClassName('myInputValue')[0];
var submitbtn = document.getElementsByClassName('myLink')[0]
inputc.addEventListener("keydown", function(e){
if(e.keyCode == 13){
submitbtn.click();
}
});
submitbtn.addEventListener("click", function(e){
alert('Hello');
});
})();
<input type="text" class="myInputValue">
<button class="myLink">submit</button>
Or you can call function for both the events
(function() {
var inputc = document.getElementsByClassName('myInputValue')[0];
var submitbtn = document.getElementsByClassName('myLink')[0]
inputc.addEventListener("keydown", function(e) {
if (e.keyCode == 13) {
test();
}
});
submitbtn.addEventListener("click", function(e) {
test();
});
})();
function test(){
alert('hello')
}
<input type="text" class="myInputValue">
<button class="myLink">submit</button>
Upvotes: 0
Reputation: 499
Create a custom event and dispatch it.
submitbtn.addEventListener("click", function(e){
var event = new CustomEvent("keydown", {
keyCode: 13
});
inputc.dispatchEvent(event);
});
Upvotes: 0
Reputation: 50844
If you don't need to get the specific event data from the enter button being pressed and instead just need to same function to run you can give your anonymous function a name such as processKey
and use that whenever you want the enter key code to run. Then when you click on your button, you can pass through 13
as the key
argument to processKey
method.
See working example below:
function processKey(key) {
if(key == 13){
alert("Entered");
}
}
(function(){
var inputc = document.getElementsByClassName('myInputValue')[0];
var submitbtn = document.getElementsByClassName('myLink')[0];
inputc.addEventListener("keydown", e => processKey(e.keyCode));
submitbtn.addEventListener("click", _ => processKey(13));
})();
<input type="text" class="myInputValue">
<button class="myLink">submit</button>
Upvotes: 1