James Hamann
James Hamann

Reputation: 862

Trying to capture a form submit event, then not capture it again

Edit: @mhodges answered the question. Jsfiddle is updated. Thank you!

I have a little calculator/donation form that I am setting up. The form is simple: one input for a number, then the submit button performs a calculation and gains a new value, at which point I want it to link to a donation page. Here's some sample code:

<form id = "donation" action = "donation/page">
  <input id = "firstNumber" placeholder = "400.00">
  <input type = "submit" id = "submit" value = "Calculate Number">
</form>

And here's the jquery I have running it:

$(document).ready(function(){
  $("#donation:not(.ready)").submit(function(e){
    e.preventDefault;
    var amount = $("#firstNumber").val() / 5;
    $("#firstNumber").val(amount);
    $("#submit").val("Donate Now!");
    $("#donation").addClass("ready");
  });
});

Edit: Spelling and a link to a JS fiddle:

JS Fiddle

So the calculator works great and the new value shows up great in the input. My problem is that the value for the submit button isn't changing and the submit button continues to perform the calculation even after getting the .ready class. I thought using the not:(.ready) selector in my jquery would fix this, but it's not. Any thoughts? Thank you!

Upvotes: 2

Views: 51

Answers (2)

mhodges
mhodges

Reputation: 11116

You need to use event delegation rather than event binding. The code would look like the following:

$(document).ready(function(){
  $(document).on("submit", "#donation:not(.ready)", function(e){
    e.preventDefault();
    var amount = $("#firstNumber").val() / 5;
    $("#firstNumber").val(amount);
    $("#submit").val("Donate Now!");
    $("#donation").addClass("ready");
  });
});

ALSO NOTE - e.preventDefault() is a function and thus needs parentheses

Upvotes: 2

Siderite Zackwehdex
Siderite Zackwehdex

Reputation: 6570

You are first selecting, then binding your function to the elements found. The list of objects found by the selector doesn't change later on. If you only wish to execute an event handler only once per element and event, try jQuery.one.

Upvotes: 0

Related Questions