Reputation: 4524
I have written two script one for Enter button click and one for change, but both events are firing, I want if enter button clicked by keyup/keydown/keypress/paste then change should not fire as well on keyup/keydown/keypress/paste only one event should fire.
$('#txtName').on('keypress keyup paste', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
AddName($('#txtName').val());
}
});
$('#txtName').on({
change: function () { AddName($('#txtName').val()); }
});
Upvotes: 1
Views: 81
Reputation: 5831
Cause you are using two events with key listener. Just use one of them keypress
or keyup
event.
And add a event.preventDefault();
for stop the event it will not trigger the change
event.
$('#txtName').on('keyup paste', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
AddName($('#txtName').val(),e);
}
});
$('#txtName').on({
change: function (e) { AddName($('#txtName').val(),e); }
});
function AddName(value,e)
{
console.log(e.type+ " - "+value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtName">
Upvotes: 2
Reputation: 5183
If the #txtName
here is an input box, then the change
event is deferred until the element loses focus and will get triggered if the value has changed from the previous state.
For your requirements, you can combine all the events on jquery.on
and add your logic in the handler as such:
$('#txtName').on('keypress keyup paste change', function (e) {
var keyCode = e.keyCode || e.which;
if (e.type == "change") {
AddName($('#txtName').val());
}
else if (keyCode === 13) {
AddName($('#txtName').val());
}
});
function AddName() {
// Your code here
}
Upvotes: 2
Reputation: 718
keypress event fire when user press a key, keyup event is fire when user release the key (after pressing). So you should use either keypress OR keyup, if you want one event fire at a time.
Upvotes: 0