te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>arrays - Calculate the sum of values in input elements using JavaScript - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

arrays - Calculate the sum of values in input elements using JavaScript - Stack Overflow

programmeradmin3浏览0评论

I'm trying to pute the sum of many inputs that are displayed, in order to make an invoice. All products that must be invoiced are recorder in my database, and I wrote this JavaScript function to calculate the total:

<script type="text/javascript">
function getItems()
 {
 var items = new Array();
 var itemCount = document.getElementsByClassName("items");
 var total = 0;
 for(var i = 0; i < itemCount.length; i++)
 {
     total = total +  document.getElementById("p"+(i+1)).value;
 }

 return total;
 document.getElementById('tot').value= total;
 }
 getItems()</script>

The problem is that I get Uncaught TypeError: Cannot read property 'value' of null on the line total = total + document.getElementById("p"+(i+1)).value;

I really do not understand why, because all my variables are declared.

I'm trying to pute the sum of many inputs that are displayed, in order to make an invoice. All products that must be invoiced are recorder in my database, and I wrote this JavaScript function to calculate the total:

<script type="text/javascript">
function getItems()
 {
 var items = new Array();
 var itemCount = document.getElementsByClassName("items");
 var total = 0;
 for(var i = 0; i < itemCount.length; i++)
 {
     total = total +  document.getElementById("p"+(i+1)).value;
 }

 return total;
 document.getElementById('tot').value= total;
 }
 getItems()</script>

The problem is that I get Uncaught TypeError: Cannot read property 'value' of null on the line total = total + document.getElementById("p"+(i+1)).value;

I really do not understand why, because all my variables are declared.

Share Improve this question edited Mar 21, 2013 at 7:08 Dan Dascalescu 152k64 gold badges332 silver badges419 bronze badges asked Nov 5, 2012 at 7:26 Stanislas PiotrowskiStanislas Piotrowski 2,69411 gold badges41 silver badges60 bronze badges 1
  • It means document.getElementById("p"+(i+1)) returns null, no element with id "p"+(i+1) was found. – Musa Commented Nov 5, 2012 at 7:29
Add a ment  | 

4 Answers 4

Reset to default 5

You already got the elements by using getElementsByClassName, why you are getting it again by id? You can try following:

function getItems()
{
    var items = document.getElementsByClassName("items");
    var itemCount = items.length;
    var total = 0;
    for(var i = 0; i < itemCount; i++)
    {
        total = total +  parseInt(items[i].value);
    }
    document.getElementById('tot').value = total;
}
getItems();​

One or more of the items with an id for "p"+(i+1) apparently does not exist. You didn't show us your HTML so we can't be more specific than that.

But, since you already have a nodeList that is an array-like list of the items from getElementsByClassName(), there is no need to get them all over again. As such, you can much more safely rewrite the code to use that and it should also protect you from trying to reference a non-existent item since getElementsByClassName() won't return null items. There are also a couple other issues:

  1. You need to convert the results to numbers before doing the addition so you are adding numbers, not strings:

    total = total + Number(items[i].value);

  2. You also need to put the return AFTER you assign the total or the assignment will not get executed:

    document.getElementById('tot').value = total; return total;

  3. And, since you don't show us your HTML, we don't know what items actually exist so you can protect your code from items that don't exist by using the actual nodeList that es back get the getElementsByClassName() call rather than retrieving items over again. All items in the nodeList that es back from that function will exist:

With these changes and some other cleanup, the whole function would look like this:

<script type="text/javascript">
function getItems() {
    var items = document.getElementsByClassName("items");
    var total = 0;
    for (var i = 0; i < items.length; i++) {
        total += Number(items[i].value);
    }

    document.getElementById('tot').value = total;
    return total;
 }
 getItems();
 </script>

try this
DEMO

<input type='text' id='p1' class='items' value='10' />
<input type='text' id='p2' class='items' value='10' />
<input type='text' id='p3' class='items' value='10' />
<input type='text' id='p4' class='items' value='10' />
<input type='text' id='tot' value='' />​

function getItems()
{
 var items = new Array();
 var itemCount = document.getElementsByClassName("items");
 var total = 0;
 var id= '';
 for(var i = 0; i < itemCount.length; i++)
 {
   id = "p"+(i+1);
   total = total +  parseInt(document.getElementById(id).value);
 }
document.getElementById('tot').value = total;
return total;
}
getItems();

You need to convert from strings to numbers when you parse the value of the inputs, and from number to string when you build the p ids.

total = total + Number(document.getElementById(id).innerHTML);
var id = 'p'+String(i+1);

Here's working code, assuming paragraphs instead of input element: http://jsfiddle/dandv/HdwZm/1/

发布评论

评论列表(0)

  1. 暂无评论