0

I'm using (all right, just starting to learn) bootstrap and javascript and jQuery. I have a rather extensive experience in other programming languages, and I like understanding what happens.

so I have a dialog box containing just one input box, and I do not want a POST action to be fired when the user hits enter. I am using a dirty trick according to me, and I'm wondering how to do this more neatly.

<div class="modal-body">
  <form enctype="multipart/form-data" class="well">
    <input id="empty" name="empty" type="hidden"/></form>
  <table width="100%">
    <tr><td width="30%">accession#.plant#</td>
        <td><input id="addendum" name="keyword" type="text"/></td></tr>
  </table>
</div>

the unused "empty" form, it's the dirty trick that works for me on firefox 27.0.1

I have tried disabling the enter key completely, as suggested by answers to similar questions, but it has a non desirable side effect according to me: when entering data in a input element, the browser will give hints. disabling the enter key makes difficult selecting among them.

mariotomo
  • 9,438
  • 8
  • 47
  • 66

3 Answers3

2

It's hard to tell without seeing the JavaScript, but you should be able to call preventDefault on the event object in JavaScript. This keeps the form from submitting, but shouldn't interfere with the type ahead behavior in browsers.

Greg Burghardt
  • 17,900
  • 9
  • 49
  • 92
0
Give the form an id and then put the id in the keypress function... It should work.
<script type="text/javascript">
    $(document).ready( function() {
        $('#[formid]').keypress(function (e) {
            if (e.which == 13) {
                e.preventdefault();
                return false;
            }
        });
    });
</script>
Martin E.
  • 267
  • 1
  • 12
0

You can use this, it will prevent form submission if no field have been inputed.

$( ".well" ).on( "submit", function() { 
  var has_empty = false;
  $(this).find( 'input' ).each(function () {
    if ( ! $(this).val() ) { has_empty = true; return false; }
  });
if ( has_empty ) { return false; }
});

EDIT: Biding it to the enter listener:

$(".well").bind("keyup keypress", function(e) {
  var code = e.keyCode || e.which; 
  if (code  == 13) {               
    e.preventDefault();
    var has_empty = false;
    $(this).find( 'input' ).each(function () {
      if ( ! $(this).val() ) { has_empty = true; return false; }
    });
    if ( has_empty ) { return false; }
  }
});
sidney
  • 2,704
  • 3
  • 28
  • 44
  • but this is a huge amount of code! my dirty trick sort of looks better, isn't it? – mariotomo Mar 04 '14 at 22:09
  • If it works, why not :) But I'm not sure if your solutions works for every browsers. If you want something strong enough, and which works everywhere, I suggest to go with my solution. Between, it is indeed long, but this is the client which executes it, and the process time is ridiculously low, it should not be a problem ;) – sidney Mar 04 '14 at 22:11