views:

30

answers:

3

I'm trying to prevent double submission using the enter key on my form, but I can't seem to re-enable the keypress after the data has been submitted. Here's a part of my code:

$(".adauga-clasa").submit(function() {
  var adaugaClasa = $('input[type=text]', this);

  adaugaClasa.keypress(function(event) { if (event.keyCode == '13') { return false; } });

  $.ajax({
    type: "POST",
    url: "/clase/do-add",
    data: dataString,
    dataType: "json",
    success: function(data) {
      // this doesn't work
      adaugaClasa.keypress(function(event) { if (event.keyCode == '13') { return true; } });           
    }
});
+1  A: 

You need to .unbind() the previous event handler (which is still bound, and still returning false before your new handler), like this:

adaugaClasa.unbind('keypress');

With this there's also no need for the new keypress handler to be added, just removing the old one will suffice.

Nick Craver
A: 

It doesn't work because you don't unbind the previous function. You just add a new one. You need to use .unbind('keypress').

Zlatev
+1  A: 

Why don't you have a boolean variable flag?

var form_submitted = False

Set it to True on submit, and check it when submitting.

Shane Reustle
this is by far the simplest and most robust way of doing it
Swizec Teller
@Swizec - It's not the same though...the original approach prevents the inputs from changing, this just prevents the `<form>` from submitting...given the OP is attaching this to textboxes, not submit buttons, this probably doesn't do what they're after :)
Nick Craver
Ah well, then binding a keypress event will do the trick :)
Swizec Teller