I want to give enter send a form

Asked

Viewed 58 times

0

Hello, I have a javascript that when clicking the "Search" button, will make a request via ajax and search for a certain value that is in the input.

What I need is, when the person type in the input and der enter, automatically click the button.

<input type="text" id="dado" name="dado" placeholder="Descrição" required/>
<button onclick="enviar('0');">Pesquisar</button>

Not this inside a form, I have to put in and give some type to the button?

That’s what I tried, but since it’s javascript that matters on the button by the onclick event, so didn’t call the function, what to do?

I have several buttons on the screen for other ajax Avascripts, and other inputs, so I would have to give id to each form, if it is something related, I would have an example for two ways of doing ?

  • The easiest would be for you to assemble the full form element, set the button as Submit and treat the Submit event from this form. The vast majority of browsers already try to submit the form by pressing enter.

1 answer

4


Below is a way to do this through javascript, insert an id on the button to force the event to click on it:

document.getElementById("dado")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("button-dado").click();
    }
});
<input type="text" id="dado" name="dado" placeholder="Descrição" required/>
<button id="button-dado" onclick="enviar('0');">Pesquisar</button>

  • 1

    Perfect, worked!

  • 1

    Magnificent! I wasn’t going to make it (:

  • Glad you solved your problem.

Browser other questions tagged

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