Pressing 'enter' on a input type="text", how?
html, javascript, jquery
Solution
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
Problem
I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code : ``` (...) <script type="text/javascript"> // Autocomplete suggestions $(function () { $("#autoCompInput").autocomplete({ source: "/Suggestions", minLength: 3, select: function (event, ui) { if (ui.item) { $("#autoCompInput").val(ui.item.value); $("form").submit(); } } }); }); // Provide search results $(function () { $("#autoCompSearch").click(function () { var searchParameters = $("#autoCompInput").val(); var jsonData = JSON.stringify(searchParameters, null, 2); window.location = "/Search?criteria=" + searchParameters; }); }); </script> (...) <input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "@ViewBag.SearchInfo"/> <a id= "autoCompSearch" href = "#" ><img src="@Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a> (...) ``` With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me? Thank you,