52

I have a search box at the top of page that makes an ajax call when a user hits the adjacent button. I am trying to update the input tag so that when a user hit the 'enter' key, the apropriate JavaScript takes place without reloading the page. The problem is that the page keeps reloading. Here is my latest attempt:

$("searchText").bind('keyup', function(event){ 
  if(event.keyCode == 13){ 
    event.preventDefault();
    $("#buttonSrch").click(); 
    return false;
  }
});

<input type='search' id='searchText' />
<input type='button' id='buttonSrch' onclick="search(document.getElementById('searchText'))" value='Search' />
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
John R
  • 2,920
  • 13
  • 48
  • 62
  • Does your `search()` function have a `return false` as well? – Mottie Jan 14 '12 at 23:06
  • 5
    Please don't edit out mistakes in your question as answers point them out - that makes the answers look wrong :) – Adam Rackis Jan 14 '12 at 23:06
  • fudgey, I tried adding 'return false;' to the search function as you suggested, but the page still reloads. – John R Jan 14 '12 at 23:11
  • I think your question only applies when is inside
    tag. Without enclosing
    tag, 'enter' does not reload page. Also, jquery 'return false' does event.preventDefault(). So you don't need both.
    – user982671 Jun 06 '15 at 19:51
  • See: https://jsfiddle.net/gabrieleromanato/eYzSX/ – Billu Jun 20 '18 at 10:37

11 Answers11

35

Don't bind to the inputs; bind to the form. Assuming the form has an ID of searchForm:

$("#searchForm").submit(function() {
    search($("#searchText").get(0));
    return false;
});

Try it out.

It can also be done with plain JavaScript:

document.getElementById('searchForm').addEventListener('submit', function(e) {
    search(document.getElementById('searchText'));
    e.preventDefault();
}, false);
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • Hmmm, in the previous version the submit and input field was never within a form tag. Maybe this is the problem. I will try... – John R Jan 14 '12 at 23:13
  • I tried... no success. $("#searchForm").submit(function() { search($("#searchText").get(0)); return false; }); ...
    – John R Jan 14 '12 at 23:27
  • @John: I added an example on JSFiddle to my answer. It works for me. – icktoofay Jan 14 '12 at 23:42
  • locally, no:
    – John R Jan 15 '12 at 00:04
  • @John: Your local example is missing a `);` at the end of the script. As is, it looks like this: `$(document).ready(function() { }`. Once that is fixed, it works for me. – icktoofay Jan 15 '12 at 00:27
  • Sorry about that icktoofay , I must be getting tired. Thank you very nuch ... up voted. – John R Jan 15 '12 at 00:42
  • The problem with this solution is when we have a grid with more than one value that we want to save... is there a way to find which input triggered the submit? – Kremena Lalova Jun 15 '15 at 18:10
  • @Kremena: Add a parameter to the anonymous function. This will be an event object. You can get at the element which triggered the event by accessing the `target` property of the event. Keep in mind that this will be a plain DOM element—you will need to wrap it into a jQuery object if you want it that way. – icktoofay Jun 20 '15 at 02:58
  • Yes this is what I ended up doing and posted my solution once I got it working. – Kremena Lalova Jun 22 '15 at 12:27
  • Thanks for this. Would you mind adding a jsfiddle to your answer that does the same thing but with plain javascript? – Musixauce3000 Mar 03 '16 at 17:59
  • @Musixauce3000: I translated the code in my answer to not use jQuery. The rest of the functionality in the fiddle can be translated too if necessary. – icktoofay Mar 21 '16 at 04:09
22

I know its a little late but I ran into the same problem as you. It worked for me using "keypress" instead of bind.

$('#searchText').keypress(function (e) {                                       
       if (e.which == 13) {
            e.preventDefault();
            //do something   
       }
});
opp
  • 1,010
  • 10
  • 17
18

Add onSubmit="return false;" on your form tag

<form onSubmit="return false;">
/* form elements here */
</form>`
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
vijayscode
  • 1,905
  • 4
  • 21
  • 37
  • didn't even have to listen to key events. this alone fixed it.+1 – Timar Ivo Batis Mar 22 '19 at 13:32
  • I had same problem on a page with lots of Bootstrap 4 forms which did not have type="submit" buttons but, instead, had type="button" buttons. The page was getting reloaded whenever enter key was pressed when cursor was inside any input text field inside those forms. This solution of adding `onSubmit="return false;"` to the form tags fixed the problem. – gsinha May 03 '20 at 10:34
  • This just prevents it from working on svelte – Xanthan Aug 04 '22 at 04:00
16

You are missing # in the selector. Try this

<input type='text' id='searchText' />

JS

$("#searchText").bind('keyup', function(event){ 
  if(event.keyCode == 13){ 
    event.preventDefault();
    //$("#buttonSrch").click(); 
    search(this.value);
  }
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
6
 $('#seachForm').submit(function(e){
      e.preventDefault();
      //do something
 });
Fresheyeball
  • 29,567
  • 20
  • 102
  • 164
  • I agree with @icktoofay, but this is a cleaner way of going about in imho. You should bind to the
    element. If you don't have a form element on your page, I question why hitting enter is having an effect as the browser will no know where to post.
    – Fresheyeball Jan 14 '12 at 23:19
  • In my case, I absolutely had to prevent the form being submitted if the user hits enter because the engine would redirect it to who knows where (Google Apps Script HTML template). `preventDefault()` did the trick. – Greg Apr 18 '13 at 16:28
  • 1
    you can even generalize it as: $('form').submit(function(e){e.preventDefault()}); – InGeek Mar 25 '14 at 18:48
5

You could set the form action attribute to javascript:void(0); that way the form doesn't post/get so the page wont refresh.

$(document).ready(function () {
  $('#form1').attr('action', 'javascript:void(0);');
});
LeeF
  • 51
  • 1
  • 1
3

Just use the "action" attribute in <form> tag. Like this

<form action="#">   // your content     </form>
ViPuL5
  • 613
  • 7
  • 9
1
$("searchText").keypress(function(event){ 
  if(event.keyCode == 13){ 
    $("#buttonSrch").click(); 
    return false;
  }
});
Raza
  • 11
  • 1
  • 1
    @PareshMangukiya A small tip: in comments, writing `[answer]` will auto-expand to that link. Example: [answer] – Tomerikoo Jan 28 '21 at 12:42
0

This is what ended up working for me. Please note that my struggle was to find the object that triggered the form submit:

$('#missingStaff').submit(function (e) {
e.preventDefault();
var comment = $(document.activeElement)[0];
submitComments(comment);

});

Kremena Lalova
  • 531
  • 1
  • 4
  • 17
0

You just need to add this:

<form @submit.prevent="search">

whatever function is triggered for search. When I press that search button search() func is triggered. That is why: @submit.prevent="search"

async search() {
  let yuyu = document.getElementById('search').value
  console.log('lsd', yuyu)
  try {
    let newRecipes = await this.$axios.$get(
      `/api/videosset/?user=&id=&title=${yuyu}&price=&category=`
    )
    this.$store.commit('CHANGE_NAV_LAYOUT', newRecipes)
  } catch (e) {
    console.log(e)
  }
},
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Bitfinicon
  • 1,045
  • 1
  • 8
  • 22
0

Does your JS execute immediately or on document ready? If it's not in a document ready the button won't exist at the time you're trying to call bind.

Davy8
  • 30,868
  • 25
  • 115
  • 173