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

Asked

Viewed 243 times

1

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

I present the input, below represented:

<input id="searchinputid" type="text" class="searchinput"
    name="txtbuscan" placeholder=" Search..." onkeyup="showUser(this.value)"
    autocomplete="off"></input>
  • Your HTML is invalid. The input tag does not accept closure. This can cause your page to behave correctly in all browsers.

2 answers

1

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

function ObterValor(e) {
   if (e.keyCode == 13) {
     return $("#searchinputid").val();
   }
}
  • and how I could save this value in a php variable?

  • You can make an ajax request, for example. (http://www.webmaster.pt/requisicoes-ajax-jquery-2216.html)

1


You can use Eventlistener to listen when a key is pressed and keycode to check which key is, and then Xmlhttprequest to send to php

Since you didn’t say if you use jquery, follow the example in js pure:

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">

Sample code from get.php

<?php

$variavel = $_GET['searchinputid'];

echo $variavel;

Browser other questions tagged

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