Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger onclick function when I press enter button? [duplicate]

I use the code below to update the url link based on user text input:

<input type="text" id="q" />
<input type="button" id="submit" value="submit" />

<script>
$(function () {
$("#submit").click(function() {
    var url = "/tag/";
    url += $("#q").val();
    window.location = url;
});
});
</script>

Right now it works pretty fine when someone clicks the submit button. What I want is to make it also work when a user press the enter button. Fiddle HERE

like image 986
Marsel Avatar asked May 08 '16 22:05

Marsel


2 Answers

Try with this:

$(document).keypress(function(e) {
 if(e.which == 13) {
    var url = "/tag/";
    url += $('#q').val();
    window.location = url;
 }
});
like image 137
Jakob Avatar answered Sep 23 '22 16:09

Jakob


You might simply use $(document).keypress() For this purpose extract your function out of .click() to avoid code replication like this:

<input type="text" id="q" />
<input type="button" id="submit" value="submit" />

<script>
$(function () {

var executeFunction = function(){
    var url = "/tag/";
    url += $("#q").val();
    window.location = url;
};

$("#submit").click(executeFunction);

$(document).keypress(function(event) {
    if(event.which == 13) {
        executeFunction();
    }
});
});
</script>

Update

An even better solution would be the use of the jquery .submit() event handler

<input type="text" id="q" />
<input type="button" id="submit" value="submit" />

<script>
$(function () {
$("#submit").submit(function() {
    var url = "/tag/";
    url += $("#q").val();
    window.location = url;
});
});
</script>
like image 42
Daniel Avatar answered Sep 23 '22 16:09

Daniel