79b4825afe5c22c7d6226037ac81ee69

Hi All,

I want to refactor (port) the following PrototypeJS code to jQuery. I'm in the process of learning jQuery and currently stuck with porting this piece of code... Any idea's?

var total = 0;

// For each fieldpair that has a child with a checked input
// we get the sibling with a text input and add that value
// to the total. 
$$(".fieldpair").each(function(fieldpair) {
   if (fieldpair.down("input:checked")) {
     var input = fieldpair.down('input:text');
     total += parseInt(input.value);		 
  }
});

Refactorings

No refactoring yet !

Aacfa176a8d73ca75b90b6375151765a

paul.wilkins.myopenid.com

September 1, 2009, September 01, 2009 13:10, permalink

No rating. Login to rate!

The following is a working translation to jQuery, where the this keyword is the fieldpair reference.

There should be a better way to do this though.

var total = 0;
// For each fieldpair that has a child with a checked input
// we get the sibling with a text input and add that value
// to the total.

$('.fieldpair').each(function () {
    if ($('input:checked', this).length) {
        var input = $('input:text', this);
        total += parseInt(input.val());
    }
});
Aacfa176a8d73ca75b90b6375151765a

paul.wilkins.myopenid.com

September 1, 2009, September 01, 2009 13:21, permalink

No rating. Login to rate!

The following seems to provide an improved flow to the code.

The comment now seems to be superfluous, as the comment says exactly what the code does. Better comments tend to explain why things occur instead.

var total = 0;
// For each fieldpair that has a child with a checked input
// we get the sibling with a text input and add that value
// to the total.

$('.fieldpair input:checked')
    .siblings('input:text').each(function () {
        total += parseInt(this.value);
    });
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

September 1, 2009, September 01, 2009 15:17, permalink

No rating. Login to rate!

If you wrote a quick inject method this would be pretty clean:

$('.fieldpair :checked ~ :text').inject(0, function(total){
  return total + parseInt(this.value)
})

Your refactoring





Format Copy from initial code

or Cancel