Reputation: 1
I have a very simple code, expecting "Enter pressed" showing in the console every time the enter key is pressed when typing in an editable table cell (CELL2).
console.log('working');
function enterKeyCheck(x) {
x.addEventListener('keypress', function(y) {
if (y.which == 13) {
y.preventDefault();
console.log('Enter Pressed')
};
});
};
<div id="test1">
<table>
<tr>
<td>CELL1</td>
<td contenteditable="true" onkeyup="enterKeyCheck(this)">CELL2</td>
</tr>
</table>
CHECKING
</div>
I was expecting The "enter pressed" message once for every enter key hit, but looks like I get multiple of them each time, and I think the message is logged as many times as the number of characters types before pressing the enter key.
Thank you.
Upvotes: 0
Views: 1680
Reputation: 705
there are some repeating things happening for using this
at the enterKeyCheck
method. Each time you click, it's firing the total clicks and consoling for the last one. To avoid that you just need to use event
instead of this
. In that case, the code would be like:
<td contenteditable="true" onkeyup="enterKeyCheck(event)">CELL2</td>
function enterKeyCheck(x) {
if (x.which == 13) {
x.preventDefault();
console.log('Enter Pressed')
};
};
If you use the above ways I think it will reach out to your requirement.
Upvotes: 0
Reputation: 1695
When you click on the cell, the onkeyup
is calling enterKeyCheck
which again has a listener for keypress, that's being fired.
You could rewrite your function to something like this, to fix the issue.
document.querySelector('#cell').onkeyup = function (e) {
if (e.keyCode === 13) { // enter, return
console.log('Enter pressed') //do something
}
};
Add an id to the cell to be recognizable.
<div id="test1">
<table>
<tr>
<td>CELL1</td>
<td contenteditable="true" id="cell">CELL2</td>
</tr>
</table>
CHECKING
</div>
Upvotes: 0
Reputation: 50291
You are attaching the event twice , once inline in html and other inside the enterKeyCheck
function. Instead of this
pass the event
object from the event handler and in the function check the event code
function enterKeyCheck(y) {
if (y.which === 13) {
y.preventDefault();
console.log('Enter Pressed')
};
};
<div id="test1">
<table>
<tr>
<td>CELL1</td>
<td contenteditable="true" onkeyup="enterKeyCheck(event)">CELL2</td>
</tr>
</table>
CHECKING
</div>
Upvotes: 2
Reputation: 684
onkeyup
is already firing enterKeyCheck
for every keypress, and you have another event listener within your enterKeyCheck
that's being called, therefore calling it twice. You should only need one of them.
Upvotes: 0