DjH DjH - 7 months ago 28
Javascript Question

Add keypress or eventlistener to input, "TypeError: ...addEventListener is not a function"

I'm working on a form where I do not want enter/return to submit the form so I used a function like this.

$('[name="form"]').keypress(function(e) {
var charCode = e.charcode || e.keyCode || e.which;
if (charCode === 13) {
e.preventDefault();
return false;
}
});


That works, but now I want to assign the enter/return to perform functions on two inputs on the form. I'm totally stuck.

To get the inputs I've tried vanilla js calling by id, jQ calling by id and then a mixer of the two with variables. I've also tried .keypress, .keydown, .keyup instead of the attachEventListener method. No matter what I do, I get this error in console.

"TypeError: ...addEventListener is not a function" (or keypress, keydown etc.)

I've also researched a good deal but can't find any solution. I appreciate any suggestions.
Here is this block of code in it's current form that's giving the trouble.

var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');

yelpInput.addEventListener("keydown", function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});

// Google
googleInput.addEventListener("keydown", function(e) {
if (e.keyCode === 13 ) {
alert('do stuff!');
}
});


Thanks

Answer
var yelpInput = $('#inputURL');
var googleInput = $('#googleURL');

yelpInput.keydown(function(e) {
    if (e.keyCode === 13 ) {                        
        alert('do stuff!');
    }
});

// Google
googleInput.keydown(function(e) {
    if (e.keyCode === 13 ) {    
        alert('do stuff!');
    }
});