How would the code below look in pure Javascript?

Asked

Viewed 48 times

3

I’m having a hard time finding a way for a function to find a variable from another function within my code as I type into a text box, even though the variable is global. I will try through the code below, but need first convert it to pure JS.

$('input[name="q"]').keyup(function(){
  console.log($(this).val());
});

1 answer

4


You can use .querySelector() to fetch the element and use .addEventListener() to observe the Event "keyup" in the target element (<input>)

The passage below expresses this reasoning:

document.querySelector('input[name="q"]').addEventListener('keyup', function(evt) {
    console.log(evt.target.value);
}, false);
<input name="q" type="text" placeholder="Digite aqui">

If you do not find an item .querySelector() returns null and therefore will make a mistake (TypeError) when trying to link a listener to "event" ... example:

    document.querySelector('input[name="q"]').addEventListener('keyup', function(evt) {
        console.log(evt.target.value);
    }, false);
<input name="xyz" type="text" placeholder="Digite aqui">

Not to run the risk of trying to attach a listener to a reference that does not exist (null), you can reference the element in a variable and then check if it "exists" (if the element was found), example:

    let inputElement = document.querySelector('input[name="q"]');
    // verificar
    if ( inputElement ) {
        inputElement.addEventListener('keyup', function(evt) {
            console.log(evt.target.value);
        }, false);
    }
<input name="q" type="text" placeholder="Digite aqui">


Sources:

  • 1

    Very clear and enlightening, Lauro! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.