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 !
paul.wilkins.myopenid.com
September 1, 2009, September 01, 2009 13:10, permalink
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());
}
});
paul.wilkins.myopenid.com
September 1, 2009, September 01, 2009 13:21, permalink
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);
});
Tj Holowaychuk
September 1, 2009, September 01, 2009 15:17, permalink
If you wrote a quick inject method this would be pretty clean:
$('.fieldpair :checked ~ :text').inject(0, function(total){
return total + parseInt(this.value)
})
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?