Submit input box data using enter key?

Asked

Viewed 416 times

1

I want you to press the button Enter the value is inserted into the HTML page using jQuery.

The code below is input simple in HTML:

<!doctype html>
<html>
  <head>
    <title>Somar Arrays</title>
  </head>
  <body>

    <section class="vetores">
      <p>Adicione números:</p>
      <input type="text"><button>+</button>
    </section>

    <section class= "imprimir"></section>

      <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
      <script src="funcao.js"></script>
  </body>
</html>

The code below, in Javascript, allows values to be entered with the mouse click, but how to make it work when I press the key enter?

var main = function() {
        "use strict";

    //Permite que os valores sejam inseridos a partir do click do mouse
        $(".vetores button").on("click", function(event){
            var $nro;

                if ($(".vetores input").val() !== "") {
                    $nro = $("<p>").text($(".vetores input").val());
                    $(".imprimir").append($nro);
                    $(".vetores input").val("");
                }
        });

    //Permite que os valores sejam inseridos a partir da tecla enter
        $(".vetores button").on("keypress", function(event){
            var $nro;

            if(event.keyCode === 13){
                if ($(".vetores input").val() !== "") {
                    $nro = $("<p>").text($(".vetores input").val());
                    $(".imprimir").append($nro);
                    $(".vetores input").val("");
                }
            }
    });

    };

    $(document).ready(main);

1 answer

1


The keypress event must be associated with the input, not the button.

Change of:

$(".vetores button").on("keypress", function(event){

To:

$(".vetores input").on("keypress", function(event){
  • Thank you very much!

Browser other questions tagged

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