最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Pressing 'enter' on a input type="text", how? - Stack Overflow

programmeradmin11浏览0评论

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,

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,

Share Improve this question asked Jun 5, 2012 at 21:37 Bastien VandammeBastien Vandamme 18.5k36 gold badges127 silver badges212 bronze badges 2
  • Also I have no problem to show an alert. I have a problem to submit my search. – Bastien Vandamme Commented 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 Commented Jun 5, 2012 at 22:10
Add a comment  | 

4 Answers 4

Reset to default 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();
    }
};

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.

To assign a keyup event in jquery

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

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");
})
发布评论

评论列表(0)

  1. 暂无评论