12

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

Jakob
  • 3,493
  • 4
  • 26
  • 42
Marsel
  • 323
  • 2
  • 11

2 Answers2

6

Try with this:

$(document).keypress(function(e) {
 if(e.which == 13) {
    var url = "/tag/";
    url += $('#q').val();
    window.location = url;
 }
});
Jakob
  • 3,493
  • 4
  • 26
  • 42
  • Instead of repeating the code you can trigger the click handler: `$("#submit").click()`. – Ram May 08 '16 at 22:19
  • I tried it but doesn't work. Cant figure out what i am doing wrong :( Could you please check the Fiddle i provided above? Many thanks ! Keep in mind that i want to use both functions (Submit Button Click + Enter Press) – Marsel May 08 '16 at 22:19
  • @Marsel try updated code – Jakob May 08 '16 at 22:19
  • @jacob it works fine. Thank you so much – Marsel May 08 '16 at 22:24
1

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>
Daniel
  • 3,541
  • 3
  • 33
  • 46
  • @downvote could you give me a hint what is wrong with my answer? I'd gladly improve it... – Daniel May 08 '16 at 22:26
  • 1
    well, upvote from me... and same question to downvoter.. don't get why our answers are not useful. – Jakob May 08 '16 at 22:41