phpmeh
phpmeh

Reputation: 1792

Cycling through an array of form elements

I am returning form elements into a form from ajax. I can count the number of elements returned, but I don't know how to cycle through them. I need to be able to get the value of each element returned.

I am pretty sure this is a basic javascript thing that I just don't know. The problem only looks more complicated with the Ajax.

My code looks like this:

    // The view page
    <html>
    <head>
    <script language="javascript">
    function calculateAlphaTotals(){
        var length = document.myForm["alpha[]"].length;
        alert( length ); // correctly outputs 3
        for( var i = 0; i < length; i++ ){
            try{
                alert( document.myForm["alpha[]"].value ); // HTML ObjectCollection 
                alert( document.myForm["alpha["+i+"]"].value ); // Object Required
            } catch( error ) { }
        }
    }
    </script>
    </head>
    <body>
    <form name="myForm" id="myFormId" method="post">
        <div id="ajaxOutputId"></div>
    </form>
    </body>
    </html>

    // The Ajax page:

    <input name="alpha[]" onchange="calculateAlphaTotals()" />
    <input name="alpha[]" onchange="calculateAlphaTotals()" />
    <input name="alpha[]" onchange="calculateAlphaTotals()" />

Upvotes: 0

Views: 443

Answers (4)

Tom
Tom

Reputation: 4180

<script language="javascript">
    function calculateAlphaTotals(){
        var els = document.myForm["alpha[]"];
        for(var i = 0, ceiling = els.length; i < ceiling; i++){
             alert(document.myForm["alpha[]"][i].value);
        }
    }
</script>

Upvotes: 0

gdoron
gdoron

Reputation: 150253

Use the index -[] operator in the right place:

var x = document.myForm["alpha[]"];
for( var i = 0; i < x.length; i++ ){
    var currentValue = x[i].value;
    alert(currentValue);
}    

Yours: document.myForm["alpha["+i+"]"] changes the string, not iterate the collection.

Upvotes: 1

Brian Glaz
Brian Glaz

Reputation: 15666

You're pretty close, but you need to change one thing. document.myForm["alpha[]"] is actually an array, so if you want to cycle through it, you need to tack your i index on the end like this: document.myForm["alpha[]"][i]

Upvotes: 1

Saket Patel
Saket Patel

Reputation: 6683

try using document.myForm["alpha[]"][i].value instead of document.myForm["alpha["+i+"]"].value

so you function will be like this

    function calculateAlphaTotals(){
        var length = document.myForm["alpha[]"].length;
        alert( length ); // correctly outputs 3
        for( var i = 0; i < length; i++ ){
            try{
                alert( document.myForm["alpha[]"][i].value ); // Object Required
            } catch( error ) { }
        }
    }

Upvotes: 1

Related Questions