how do I capture the value of this input when I click enter in the input and without using form?

1

How do I capture the value of this input when I click enter on input and without using form?

input , shown below:

<input id="searchinputid" type="text" class="searchinput"
    name="txtbuscan" placeholder=" Search..." onkeyup="showUser(this.value)"
    autocomplete="off"></input>
    
asked by anonymous 03.11.2017 / 17:20

2 answers

1

You can use EventListener to listen when a key is pressed and keyCode to check what the key is, then XMLHttpRequest to send to php

As you have not said if you use jquery, follow the example in pure js:

var input_busca = document.querySelector('#searchinputid')//Seleciona a input

input_busca.addEventListener('keypress', function (e) {
    var key = e.which || e.keyCode;
    if (key === 13) { // 13 = verifica se a tecla é o enter, 13 = enter
      alert("Valor local: " + input_busca.value)//Exibe o valor local
      var xhr = new XMLHttpRequest();
      xhr.open('GET', 'get.php?searchinputid=' + input_busca.value, true);// Informações para enviar ao php
      xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      xhr.onload = function () {

          alert("Resposta servidor: " + this.responseText);//Resposta do servidor
      };
      xhr.send();
    }
});
<input id="searchinputid" type="text" class="searchinput"
name="txtbuscan" placeholder=" Search..." autocomplete="off">

Get.php sample code

<?php

$variavel = $_GET['searchinputid'];

echo $variavel;
    
03.11.2017 / 17:57
1

Use the keyCode to capture the enter and retrieve the value of the field by calling the function at some key event (keyPress, keyDown or keyUp). Ex:

function ObterValor(e) {
   if (e.keyCode == 13) {
     return $("#searchinputid").val();
   }
}
    
03.11.2017 / 17:26