Hello. I have a text field, not even a textarea, but just an input, there is no button and it should not be (as intended). I need that when you press ENTER in the text field, it performs the ajax function.

<input placeholder='Введите сообщение...' id='txtmess'> function gomess() { //Отправить сообщение var id = $("#idus").text(); var txtmess = $("#txtmess").val(); $.ajax({ type: 'POST', url: '/obr/mess.php', data: 'idus='+ id +'&txt='+ txtmess, success: function(data) { alert(data); }, error: function(xhr, str){ alert(data); } }); } 

I found such a function onkeydown , but I don’t know how to use it ... Tell me some functions or preferably a script for an example.

  • And what prevents to see an example in the documentation? - ilyaplot 1:58 pm

2 answers 2

 document.addEventListener('DOMContentLoaded', e => { document.querySelector('#txtmess').addEventListener('keydown', function(e){ if('key' in e){ if(e.key.toLowerCase() !== 'enter') // Если свойство KeyboardEvent.key не равно enter - выходим return; }else{ if(e.keyCode !== 13) // Более грубое, но более поддерживаемое свойство, 13 - enter return; } // Иначе убираем поведение браузера и делаем свои делишки e.preventDefault(); console.log('AJAX', this.value); }); }); 
 <input placeholder='Введите сообщение...' id='txtmess'> 

  • obrphp.js: 3 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined - Sasha Osipov
  • @ Sasha Osipov, apparently using a browser without the support of the key property. Rewrote the example under the old browsers. Although it is better to use Babel and write normal code. - user207618 pm
  • Well, I don’t know, the browser doesn’t seem to be old ... yandex.brower latest version - Sasha Osipov
  • But on my time it works, on others it will be? - Sasha Osipov
  • In all the others - certainly not, in the majority - most likely yes. - user207618 2:26 pm

Assign the function to the button, for example:

 document.onkeyup = function (e) { e = e || window.event; if (e.keyCode === 13) { alert("Вы нажали Enter!"); } // Отменяем действие браузера return false; } 
  • The fact is that the buttons should not be for style ... It is not desirable to do under hidden ... Extra strings. - Sasha Osipov
  • @ Sasha Osipov, what is the connection with the button and the answer? - Grundy
  • "Tie the function to the button " - Sasha Osipov
  • I meant enter - Evgeniy A