Jquery回归NaN,有什么想法吗?

时间:2009-12-21 10:30:45

标签: jquery

HTML code:

<form id="hostadd" action="addmoney.php?taskid=12" method="post" onSubmit="return false">
<input type="hidden" name="mode" value="" />
current unit price:$
<input id="unitprice" name="unitprice"  type="text" size="5" maxlength="6" value= 0.50 />&nbsp
Shortfall:<input id="shortfall" type="text"  name="shortfall" size="4" maxlength="6" value=80 />
<input id="add_price" type="submit" value="Submit" onclick="Adjust()"/></form

Jquery代码:

 function Adjust(){
        $totalprice=parseFloat($('unitprice').val())*parseInt($('shortfall').val());
          alert($totalprice);

        };

当我测试时

var unitPrice = $('#unitprice').val();
alert(unitPrice);
var shortFall = $('#shortfall').val();
alert(shortFall);

我收到了两个空白警报。

4 个答案:

答案 0 :(得分:6)

您正在寻找HTML'缺口'和'unitprice':

<shortfall></shortfall>
<unitprice></unitprice>

你的意思是这样做吗?也许你是一个班级或ID selctor?

$('.unitprice').val() //class
$('#unitprice').val() //id
$('.shortfall').val() //class
$('#shortfall').val() //id

尝试查看每个组件以查看哪个组件失败。

alert($('#unitprice').val());
alert(parseFloat($('#unitprice').val()));
alert($('#shortfall').val());
alert(parseInt($('#shortfall').val(),10);

另外,将基数传递给parseInt()(注意:下面我假设你想要小数,所以使用10)

parseInt($('#shortfall').val(),10)

虽然默认值是10,但危险的是不要规定它。如果传递零填充数字,则praseInt采用Octal。

alert(parseInt(010)); // alerts '8'
alert(parseInt(010),10); // alerts '10'

答案 1 :(得分:1)

jQuery $函数使用类似CSS的选择器。因此$('unitprice')会查找元素<unitprice />。但是当你使用HTML时,没有这样的东西!

您的意思是$('#unitprice'),指的是id unitprice的任何元素。

答案 2 :(得分:0)

你可以像这样提醒吗?

function Adjust(){
    alert([$('unitprice').val(),$('shortfall').val(),$('unitprice').val().length,$('shortfall').val().length]);
}

我相信其中一个值可能包含非数字部分

答案 3 :(得分:0)

您最有可能抓住无效值。检查unitPrice和shortFall的内容:

var unitPrice = $('unitprice').val();
alert(unitPrice);
var shortFall = $('shortfall').val();
alert(shortFall);

其中一个很可能是空的或显示无效的数字。

相关问题