Submit data from an input box using the enter key?

1

I want the value to be inserted into the HTML page using jQuery by pressing Enter .

The code below is input simple 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><scriptsrc="funcao.js"></script>
  </body>
</html>

The code below, in JavaScript, allows values to be entered with the mouse click, but how do I work when I press 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);
    
asked by anonymous 02.10.2015 / 23:30

1 answer

1

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

Switch from:

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

To:

$(".vetores input").on("keypress", function(event){
    
03.10.2015 / 02:10