Karyn Cassio wrote:
Alrighty, now I'm home and actually looking at the code surrounded by books. I assume the code below (with modifications of course) should be replacing my javaScript code.
However, I'm not sure how I call this from my form.
I was calling the javascript with an onchange attribute of a textfield.
(BTW, all Earl's assumptions below were exactly correct.)

The name of my module is compute_items. This is how I stated the jquery function.
Drupal.behaviors.compute_items = function() {
//code stuff
}


I should have explained the code better, because one thing jQuery does is not obvious, but incredibly freaking awesome.

This piece of code right here is one of the amazing things jQuery can do for you:
$('css identifier').change(function() { /* code */ });

That actually is the same as calling onchange from within your HTML, except you do not have to pollute your HTML with javascript at all. What that does is bind a 'change' event to everything with that identifier. That's why we put a single class="line-item-quantity" on every quantity, so they have a unique ID and a non-unique class. That class binds the javascript. HTML and javascript become separated, resulting in vastly easier maintenance and understandability. Plus, you are safe from future use with AJAX, since by embedding this in a behavior, your change binds will be called properly even if the HTML is added via an AJAX (or AHAH) call.

Drupal.behaviors.myBehaviorFunction = function() {
  $('.line-item-quantity:not(.line-item-processed)')
    .addClass('line-item-processed') // Ensures we do only process once
    .change(function() {
      // The id of this should be edit-quantity-ID so we use replace
      // to get the base id:
      var id = $(this).attr('id').replace('edit-quantity-', '');
      var price = $('edit-price-' + id).val();

      var subTotal = id * price; // Do your actual calculation here.

      $('edit-subtotal-' + id).val(subTotal);
    });
};



Reply via email to