Jquery returns NaN,any idea?
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 /> 
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 code:
function Adjust(){
$totalprice=parseFloat($('unitprice').val())*parseInt($('shortfall').val());
alert($totalprice);
};
When I test
var unitPrice = $('#unitprice').val();
alert(unitPrice);
var shortFall = $('#shortfall').val();
alert(shortFall);
I got two blank alerts.
You're looking for an HTML 'shortfall' and 'unitprice':
<shortfall></shortfall>
<unitprice></unitprice>
Do you mean to do this? Maybe your after a class or ID selctor?
$('.unitprice').val() //class
$('#unitprice').val() //id
$('.shortfall').val() //class
$('#shortfall').val() //id
Try looking at each individual component to see which is failing.
alert($('#unitprice').val());
alert(parseFloat($('#unitprice').val()));
alert($('#shortfall').val());
alert(parseInt($('#shortfall').val(),10);
Also, pass the radix to parseInt() (note: below I assume you are wanting decimal, so use 10)
parseInt($('#shortfall').val(),10)
Although the default is 10, its dangerous not to stipulate it. If a zero left-padded number gets passed then praseInt assumes Octal.
alert(parseInt(010)); // alerts '8'
alert(parseInt(010),10); // alerts '10'
The jQuery $
function eats a CSS-like selector. So $('unitprice')
looks for an element <unitprice />
. But as you're working with HTML, there is no such thing!
What you mean to say is $('#unitprice')
, referring to any element with the id
unitprice
.
Could you put alert there like this?
function Adjust(){
alert([$('unitprice').val(),$('shortfall').val(),$('unitprice').val().length,$('shortfall').val().length]);
}
I believe one of the value might have non digits parts
You're most likely grabbing an invalid value. Check the contents of unitPrice and shortFall:
var unitPrice = $('unitprice').val();
alert(unitPrice);
var shortFall = $('shortfall').val();
alert(shortFall);
Most likely one of these will be empty or show an invalid number.
精彩评论