Duplicating JQuery/Javascript functions
<p>I have a jquery/javascript function that creates an array to be placed in a form's hidden field. However, this is a nested form and so I need to invoke this function many times to populate the hidden field for all the children: <code>test_suite_run[test_runs_attributes][//id][packages_id]</code>. This means that I need to run this function with a different child id each time.</p>

<p>I have added <code>//id</code> to indicate the only differences between the many function calls. I do not know how to duplicate this function without copying it many times manually and replacing //id with the indexes 0...n, for each nested child instance. Could this somehow be done by passing parameters to the javascript function?</p>

<p>Sorry if this a little confusing, I will be happy to explain in more detail if needed.</p>

<p>JQuery Function</p>

<pre><code>$(document).ready(function () {

    arr = new Array();

    $(document).on('change', 'select[id ^="s_package//id"]', function () {
        var arr = $('select[id ^="s_package//id"]').map(function () {
            return this.value
        })

        result = ""

        for (j = 0; j &lt; arr.length - 1; j++) {
            result += (arr[j] + ", ");
        }

        result += (arr[arr.length - 1])


        $("input[name='test_suite_run[test_runs_attributes][//id][packages_id]']").val(result);

    });
});
</code></pre>
