douqiang5163 2013-07-25 18:36
浏览 49
已采纳

求和文本输入,其中输入数量基于for循环而变化

Okay so here's the problem. I currently have a javascript that successfully sums all of the input boxes.

    <script>
    function myFunction(tBox)
    {
    var a=document.getElementById("hous1");
    var b=document.getElementById("hous2");
    var c=document.getElementById("hous3");
    w=Number(a.value);
    x=Number(b.value);
    y=Number(c.value);
    t=w+x+y;
    document.getElementById("test").innerHTML=t;
    }
    </script>

Where the number of text input boxes are dynamically created and given unique names based on:

   <?php
   for ($i=1; $1<=$housingcount; $i++){
   echo '<input size="',11,'" type="text" name="cavqty',$i,'" id="hous',$i,'" onchange="myFunction(value)"/>
   ?>

Where $housingcount simply count the number of rows that match the mysql query. Also, the function is simply outputted using:

    <p id="test"></p>

This code works fine as long as the number of text input boxes equals three. My question is how do I write my javascript to be able to take any number of text inputs, instead of being limited to a predefined number, such as three?

  • 写回答

2条回答 默认 最新

  • dongxiezhi0590 2013-07-25 18:46
    关注

    You'll have to examine all input elements and examine their name, checking for the prefix "hous". For example:

    var sum = 0;
    
    var elts = document.getElementsByTagName('input');
    for( var i=0; i<elts.length; i++ ) {
        var elt = elts[i];
        if( elt.id && elt.id.indexOf( 'hous' ) === 0 ) sum += Number( elt.value );
    }
    
    console.log( sum );
    

    This solution doesn't need jQuery. See it in action here:

    http://www.codepen.io/anon/pen/xmrGu

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?