0

I need to access the values of a number of fields in my page and perform the same calculations on them. I would like to do something like this, allowing me to dynamically access different form elements, but I cannot get it to work:

function numInFamily(famID) {
    var numAdults;
    var numChildren;
    var adultFieldID;
    var childFieldID;

    adultFieldID = 'numAdultsFam' + toString(famID);
    childFieldID = 'numKidsFam' + toString(famID);

    numAdults = parseInt(document.getElementById(adultFieldID).value,10);
    numChildren = parseInt(document.getElementById(childFieldID).value,10);

    return numAdults + numChildren;
}

Could anyone explain how I can dynamically reference these elements?

0

1 Answer 1

1

There is no built-in toString global function. But you don't need such a function, since the + operator does the string conversion automatically. Just replace the first two assignments with this:

adultFieldID = 'numAdultsFam' + famID;
childFieldID = 'numKidsFam' + famID;

Also, you can rewrite the function like so:

var numInFamily = (function () {     
    function getVal ( id ) {
        return parseInt( document.getElementById( id ).value, 10 );
    }

    return function ( famID ) {
        return getVal( 'numAdultsFam' + famID ) + getVal( 'numKidsFam' + famID );
    };    
}());

This will remove the code repetition.

Sign up to request clarification or add additional context in comments.

3 Comments

loved the 5 different versions of your answer you posted... :)
@trex005 Hehe, I keep improving it until I'm satisfied.
@ŠimeVidas- thanks! The problem was indeed with the toString(). Changing that alone solved the issue. I appreciate the further guidance on streamlining the code as well.

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.