Frage

I am looking for a way to sum column values that have been dynamically added into a table via dropdown menus referencing global arrays. Below is the code that I have written, and here is the link for the functioning example: jsFiddle. I am new to JavaScript, and everything I know I have been teaching myself so please be patient, and thank you in advance for your help.

<!DOCTYPE html>
<html>
    <head>
        <title> </title>
        <script> 
            var x= ["",1,2,3,4,5,6,7,8,9,10];
            var y= ["",4,6,3,4,5,6,7,8,9,10];
            var z= ["",1,2,3,4,5,6,7,8,9,10];
    </script>
     <script>
       function fill(){
            var si= document.getElementById('ddone').selectedIndex;
            if (si!==0){
                var a= x[si];
                var b= y[si];
                document.getElementById('one').innerHTML=a;
                document.getElementById('two').innerHTML=b;
            }};   
        </script>
        <script>
        function fill2(){
            var si2= document.getElementById('ddtwo').selectedIndex;             
            if(si2!==0){
                var c=z[si2];
                var d=z[si2];
                document.getElementById('three').innerHTML=c;
                document.getElementById('four').innerHTML=d;
            }};
        </script>
        <script>
            function total(){
                var w= parseInt(document.getElementById('one').value,10);
                var x= parseInt(document.getElementById('two').value,10);
                var y=parseInt(document.getElementById('three').value,10);
                var z= parseInt(document.getElementById('four').value,10);
                document.getElementById('five').innerHTML=w+y;
                document.getElementById('six').innerHTML=x+z;
};
        </script>
    </head>
    <body>
<select id='ddone' onchange= 'fill()'>
    <option></option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
</select>
<select id='ddtwo' onchange='fill2()'>
    <option></option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
</select>
<table border=1px width=25%>
    <tr>
        <td id='one'></td>
        <td id='two'></td>
    </tr>
    <tr>
        <td id='three'></td>
        <td id='four'></td>
    </tr>
    <tr>
        <td id='five'></td>
        <td id='six'></td>
    </tr>
</table>
<button id='button' onclick='total()'>total</button>
</body>
</html>
War es hilfreich?

Lösung

Switch value to innerHTML and your code will work perfectly. See this Fiddle for proof: http://jsfiddle.net/Nt9nC/7/

Andere Tipps

The way you are extracting the integers to sum doesn't look right. If you want to get the text within a td element try innerText, like this:

parseInt(document.getElementById('one').innerText,10)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top