15

I have a input text and I apply it typeahead plugin for suggesting items, but when I press enter key on input text it submit form.

How can I prevent form submit using twitter bootstrap typeahead plugin?

paganotti
  • 5,591
  • 8
  • 37
  • 49

6 Answers6

24

You can target that specific input by adding an ID to it and simply removing the keydown event for enter like so:

JS

$(document).ready(function() {
  $('form input').keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});
Andres I Perez
  • 75,075
  • 21
  • 157
  • 138
  • 2
    You may not want the `return false`. @See http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ – Snekse May 12 '14 at 14:49
  • 1
    Maybe @paganotti wants to press enter key to submit form on others input and ignore the tag input only. – hieund Jan 05 '16 at 03:06
3

The first answer didn't worked for me, maybe because of updating the typeahead plugin, but I did passed the problem by using the 'alternative' input created by typehead:

$(".twitter-typeahead > input").focus(function(){
    //disable btn when focusing the input
    $("#my_submit_button").prop('disabled', true);
}).blur(function(){
    //enable btn when bluring the input
    $("#my_submit_button").prop('disabled', false);
});
Tariq
  • 2,853
  • 3
  • 22
  • 29
2

According to the documentation, you can set the option confirmKeys to something else than return (13) :

$('input').tagsinput({
   confirmKeys: [188, 32, 39],
});

However, a smarter way to go about this is to prevent sending the form on enter.

Community
  • 1
  • 1
adrien
  • 504
  • 1
  • 7
  • 17
2

I have same problem in my project using CodeIgniter and bootstrap here i found the solution and it works.

Just add onsubmit="return false;" in the form, like this:

<form id="frmcrud" method="post" onsubmit="return false;">
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
Zulqarnain
  • 21
  • 3
  • This was what I needed. Further I wanted clicking the search icon or pressing enter to trigger the search (using documented `trigger('input.typeahead')` ) without a form submission (at least for now) so extended onsubmit to trigger the search event: `onsubmit="console.log('trigger manual search of .js-typeahead-frmcrud'); $('.js-typeahead-frmcrud').trigger('input.typeahead'); return false;"` – TamW Oct 15 '19 at 23:12
1

The best way I've found to approach this is not to use a submit input. Use a button input instead and add some js to submit the form when it's clicked.

$('#my_submit_button').click(function(){
    $(this).parents('form').submit();
});
Jim Ready
  • 11
  • 1
0

Use this

$('.bootstrap-tagsinput input').keydown(function( event ) {
 if ( event.which == 13 ) {
    $(this).blur();
    $(this).focus();
    return false;
 }
})
ar.gorgin
  • 4,765
  • 12
  • 61
  • 100