[development] Form API and Javascript stuck

Karyn Cassio karyn at karyncassio.com
Sun Feb 21 21:40:48 UTC 2010


Earl,

Excellent!! That totally makes sense, thanks.

Okay so this begs the question that plagues me constantly, why jquery  
vs JavaScript? And where should I concentrate my learning in this area?

FYI, at the bookstore now.

Thanks,

Karyn
Sent from my Phone

On Feb 21, 2010, at 2:22 PM, Earl Miles <merlin at logrus.com> wrote:

> Karyn Cassio wrote:
>> Hi Everyone,
>> I hope you are enjoying your weekend and not working too hard.
>> I'm still trying to get my head around js, and was hoping someone  
>> may have some insights to help me with the next steps on a form I  
>> am creating.
>> I have an order form that is going to be dynamically created.
>> I am able to successfully pass the quantity value upon user input  
>> for field 1.
>> Basically I'm using onchange() to pass the quantity value to the  
>> script.
>> The id of the price field is of the format unit-price-0, unit- 
>> price-1, etc.
>> Each line item's subtotal should update before going onto the next  
>> line item.
>> Here's the js function. Each line item has its own unit-cost,  
>> quantity, and subtotal.
>> Any help would be so appreciated.
>
> Let's assume that you've set up the ids so that they all match:
>
> 1) Each line item has a unique, probably numeric id.
> 2) The id of all the form fields for each line item is carefully
>   crafted such that the quantity will be "edit-quantity-ID", the
>   price will be "edit-price-ID" and the subtotal will be
>   "edit-subtotal-ID"
> 3) The quantity is a textfield. The price is either a disabled  
> textfield
>   so that the user cannot change it, or a hidden field. The subtotal
>   is similar.
> 4) Each line item quantity has this class: 'line-item-quantity'.
>
> You would then create a .js file using this code. Note that I am  
> using jQuery to create simpler code, so if you're not familiar with  
> jQuery it may not be immediately understandable, but it would be  
> very valuable to learn some as use of jQuery significantly increases  
> javascript productivity.
>
> For example's sake I am butchering the calculation to be as simple  
> as possible. Judging from your code it needs to be a touch more  
> complex than this, but you can handle that I am sure.
> ----
>
> // You would put this inside a Drupal behavior:
> 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);
>    });
> };


More information about the development mailing list