I am getting NaN error while clicking radio button first. The page have a3 radio button when I click that 1st button it saya NaN and remaining 2 buttons has no response
this is my HTML
<input type="hidden" name="totalamount" id="totalamount" value="<?php echo get_total_amount();?>" /
<input type="radio" name="rmr" id="payment1" value="3" onclick="updatepayment(this.value)" />
<input type="radio" name="rmr" id="payment2" value="5.5" onclick="updatepayment(this.value)" />
<input type="radio" name="rmr" id="payment4" value="10" onclick="updatepayment(this.value)" />
<div id="finalamount">
</div>
also I have mentioned my JS
$(document).ready(function(){
$('input[name=rmr]').click(function () {
//make sure one is checked
if($('input[name=rmr]:checked').length > 0) {
$('#finalamount').html($("#totalamount").val() * $("input[name=rmr]:checked").val());
}
});
});
Three things:
1) As you’re using the amount from the “totalamount” element, one has to ask: Are you sure that
…is outputting a valid number? Because if not, then the code
…will indeed result in
NaN. The*operator will try to convert both of its operands from strings to numbers, and of course if the value output by that PHP code isn’t a valid number (for instance, if it’s “$0.00” or something), the result of the conversion will beNaN. AndNaNtimes anything isNaN.This example of an invalid amount in the “totalamount” element yields something that looks a lot like the behavior you describe. (That code isn’t identical to yours, I did some very light refactoring, see below. But for the purposes of demoing an invalid number, it doesn’t matter.)
2) There’s no
>at the end of that hidden input in the text of your question. If you did a direct copy-and-paste, I wonder if that could be the problem?3) As you’re using jQuery, there’s no need for the
onclickattributes. Instead:…assuming you want
updatePaymentcalled every time.Live example
Folding
updatePaymentinto the mainclickbehavior lets you avoid any issues that may exist with the order in which DOM0 (onclickattribute) handlers and DOM2 handlers (the ones used with jQuery) are called.