2014-10-18 2 views

답변

1

당신은

$(document).ready(function() { 
 
    $('#btn_res').click(function() { 
 
    var str = 0; 
 
    $('#calculate').find("input[type=text]").each(function() { 
 
     //need to use .val() 
 
     //also need to convert it to a numerical value for addition else string concatenation will be done 
 
     str += (+$(this).val() || 0); 
 
    }) 
 
    $('#result').text(str); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table id="calculate"> 
 
    <tr> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    </tr> 
 
</table> 
 
<button id="btn_res">Sum</button> 
 
<div id="result"></div>
당신이 폼 입력 필드를 받고 bacause

+0

@Sadikhasan no ... 값을 숫자 값으로 변환하는 중 ... –

0

사용 val()

$('#btn_res').click(function(){ 
      $('#calculate').find("input[type=text]").each(function(){ 
       str+=$(this).val(); 
      }) 
      $('#result').text(str); 
     }); 
0

내 자신의 제안은 다음을 것입니다 값이 필요합니다

$(document).ready(function() { 
 
    $('#btn_res').click(function() { 
 
    // find all the relevant input elements directly (no need 
 
    // to use 'find()'; then iterate over those elements with 'map()': 
 
    var str = $('#calculate input[type="text"]').map(function() { 
 
     // this returns the value of the input (as a number) or a 0 (if 
 
     // the input is not a valid number): 
 
     return parseFloat((this.value || 0)); 
 
    // 'get()' converts the object to an array, 
 
    // 'reduce' reduces the array to a single result: 
 
    }).get().reduce(function(a, b) { 
 
     // returns the sum of the array's elements: 
 
     return a + b; 
 
    }); 
 
    $('#result').text(str); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table id="calculate"> 
 
    <tr> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    </tr> 
 
    <tr> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    <td> 
 
     <input type="text" /> 
 
    </td> 
 
    </tr> 
 
</table> 
 
<button id="btn_res">Sum</button> 
 
<div id="result"></div>

참고 :

관련 문제