0

HTML/PHP:

echo "<input type='checkbox' id='chk_esitmate' onchange='calculate_estimate(this);' 
name='" . $row['id'] ." value=". ($row['value'] ? $row['value']: '0') .
"'/>";

所以每个看起来像:

<input type='checkbox' id='chk_estimate' onchange='calculate_estimate(this);' name = '14' value=40/>

JavaScript:

var estimate = 0;

function calculate_estimate(elem)
                    {
                        var value = parseInt(elem.value, 10);
                        var status = jQuery('#span_estimate');  
                        if (elem.checked)
                        {   
                        window.estimate += value;
                        status.html(window.estimate);
                        }
                        else {
                        window.estimate -= value;
                        status.html(window.estimate);   
                        }
                    }

但是,每次我单击复选框时,它都会返回 NaN(不是数字)。有谁知道我哪里出错了?我用过 parseInt

4

5 回答 5

1

在这里为我工作 - http://jsfiddle.net/atif089/NyA4H/

确保calculate_estimate在页眉而不是页脚中定义。

于 2013-06-27T06:45:25.317 回答
0

既然您已经在使用 jQuery,为什么不这样做:

var estimate = 0;

$('#chk_estimate').click(function() {

    var value = $(this).val();

    // do your stuff in here

});
于 2013-06-27T06:42:41.583 回答
0

你可以使用javascript来知道复选框是否被选中

if(document.getElementById('chk_estimate').checked==true)
{
var num=document.getElementById('chk_estimate').value;
        alert(num);  
}
于 2013-06-27T06:51:05.180 回答
0

鉴于我无法直接访问您的文件,这个答案主要是在黑暗中拍摄,但它来自过去的经验。正如@SubirKumarSao 所说,如果它遇到的第一个字符无法转换为数字,则 parseInt 将抛出 NaN。这使我相信您从另一个网站复制了一个隐藏字符。在处理此类错误时最常见的是这种情况,当然该字符也可能存在于您的$row数组中。除此之外...

echo "<input type='checkbox' id='chk_esitmate' onchange='calculate_estimate(this);' 
name='" . $row['id'] ." value=". ($row['value'] ? $row['value']: '0') .
// missing quote here  ^ and ^ here
"'/>";

这条线被窃听了;您在结束双引号之后忘记了单引号,在开始双引号之前,我留下了评论以指示丢失的单引号应该在哪里。

这条线应该是什么样子:

echo "<input type='checkbox' id='chk_esitmate' onchange='calculate_estimate(this);' name='" . $row['id'] ."' value='". ($row['value'] ? $row['value']: '0') ."'/>";
于 2013-06-27T07:06:33.753 回答
0

好吧,我已经解决了这个问题,这是一个我不明白的错误。

我在页面上有 javscript 函数:calculate_estimatecalculate_remaining.

我设置了全局变量var estimate = 0;

在脚本的最顶部,然后我将calculate_remaining函数放在其下方,然后在其下方是calculate_estimate函数。

我不知道为什么这会影响它,因为第一个函数不使用estimate variable

很抱歉浪费了您的时间,谢谢您的帮助

于 2013-06-27T07:25:56.433 回答