0

I am too new at javascript .. and have a problem with a simple coffee-script.

Script monitors 2 fields on a form and updates a third if the either of them changes. There "n" rows of the same type in the form. here is the code

    line_pre = "#po_polines_attributes_"
    watched  = [ "_qty", "_unit_price"]
    UpdateTotal = (ln)  ->
        jQuery  ->
          e1 = line_pre + ln +  watched[0]·
          e2 = line_pre + ln +  watched[1]
          new_total = $(e1).val()*$(e2).val()
          res = line_pre + ln + "_total_price"
          $(res).val(new_total)
     #   
     for indx in [0, 1, 2]
        do  ->  
           for w_fld  in watched
              do ->
                jQuery ->
                   $(line_pre + indx + w_fld).focusout ->
                      UpdateTotal(indx)

Code runs but only updates the last row of the data when qty or u_p are changed. I can't figure out why.

Also .. can anyone suggest how to find # of elements containing a string in jQuery/coffee $("input[name~='search_str']").length() doesn't work .. it appears that the returned element doesn't have "length/size" function.

1 Answer 1

1

Your dos are missing something: the loop values as arguments.

The function wrapper that do provides in something like this:

for i in a
  do -> ...

doesn't do much since the do's function will still be sharing the same i variable just like this JavaScript does:

for(i = 0; i < a.length; ++i)
  (function() {
    ...
  })();

But, if the do function gets i as an argument:

for i in a
  do (i) -> ...

then everything changes and you start doing what do is intended to do:

for(i = 0; i < a.length; ++i)
  (function(i) {
    ...
  })(i);

Notice how this do (i) -> version forces i to be evaluated when calling the function so that you're no longer working with the shared i.

Applying this to your loops yields:

for indx in [0, 1, 2]
  do (indx) ->
    for w_fld  in watched
      do (w_fld) ->
        jQuery ->
          $(line_pre + indx + w_fld).focusout ->
            UpdateTotal(indx)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for a quick response and full explanation -

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.