11

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,

2
  • Also I have no problem to show an alert. I have a problem to submit my search. Jun 5, 2012 at 21:54
  • You should be able to use the solution below and replace the $("yourFormId").submit(); with your own logic ie window.location ...
    – workoholic
    Jun 5, 2012 at 22:10

4 Answers 4

17

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();
    }
};
2
  • In my case I had to change $("yourFormId").submit(); by var searchParameters = $("#autoCompInput").val(); var jsonData = JSON.stringify(searchParameters, null, 2); window.location = "/Search?criteria=" + searchParameters; Jun 5, 2012 at 22:29
  • @BastienVandamme Or you could just add a method="GET" to your form tag and it would do all that for you automatically.
    – PRMan
    Aug 13, 2020 at 23:40
8

With similar HTML:

<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />

This script (which uses the latest jQuery 1.7.2) should do it:

$('#mySubmit').click(function() {
    alert('Submitted!');
    return false;
});

$('#myTxt').on('keyup', function(e) {
    if (e.keyCode === 13) {
        $('#mySubmit').click();
    }
});

Here's a working example.

3

To assign a keyup event in jquery

 $("#autoCompInput").keyup(function(event) {
                if (event.keyCode==13) {
                    alert('enter key');
                }
            });
2

I think there is a better and more standard solution to this type of problem.

you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):

<form id="idForJqueryOnly" action="/Search" method="GET">
  <input type="text" name="criteria" value="someuserinput"/>
  <button type="submit"><img src="...")" alt="Search" /></button>
</form>

This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this: http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form. Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".

If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:

$("#idForJqueryOnly").submit(function(){
   // here you can do stuff like serialize the form, or sanitize the input of tue user.
  var data = $("#idForJqueryOnly").serialize();
  $("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());

  // if you return false, the form will not submit, say, for validation errors:
  return customValidator.isFormValid("#idForJqueryOnly");
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.