Simple Percentage Calculation Of An Input Field With Jquery
I'm building a PayPal form that the user enters the amount and after that transfered to paypal, everything is working fine but i need to add a calculation plugin to do the followin
Solution 1:
Is there a reason you use jQuery()
instead of $()
?
Also, you should really cache your selected elements so you don't have to query the DOM multiple times for the same element.
Here's how I would do it:
$(function() {
// the minimum required value to be entered.// in this case PayPal takes $0.35 from a $1// donation, hence we ask for at least $1.35var minimum_value = 1.35;
// cache elements that are used at least twicevar$amount = $("#input_amount"),
$msg = $("#msg"),
$commission = $("#site_commission_box");
// attach handler to input keydown event$amount.keyup(function(e){
if (e.which == 13) {
return;
}
var amount = parseFloat($amount.val()),
commission = amount*0.02;
if (isNaN(commission) || isNaN(amount)) {
$msg.hide();
$commission.hide();
return;
}
if (amount <= minimum_value) {
$commission.hide();
$msg
.text("PayPal takes $0.35 commission for a $"+amount+" donation.")
.fadeIn();
} else {
$msg.hide();
$commission
.fadeIn()
.find("span")
.text((amount-commission).toFixed(2));
}
});
// attach handler to the form submit event
$('#form_paypal').submit(function() {
// check if there is an amount enteredif ($amount.val() > null) {
// is the amount equal to or higher than the minimum_value?if ($amount.val() < minimum_value) {
// need more amount// show more amount error$msg
.addClass("icon_warning_red")
.text("Please enter an amount and try again.")
.fadeIn();
returnfalse; // prevent the form from submitting
}
else {
// amount is more than minimum_value// show activity$msg
.removeClasss("icon_warning_red")
.html('<img src="loader.gif" align="middle" alt="load"/> Transferring to PayPal, please wait...')
.fadeIn();
returntrue; // submit the form
}
}
else {
// no amount entered at all// show no amount error;$msg.addClass("icon_warning_red").fadeIn();
returnfalse; // prevent the form from submitting
}
});
});
You can see a working example here, there you can see the changes I did in the HTML as well.
Solution 2:
You have to add a event-handler for a change event. Everytime if the input value is changed the discount is recalculated. See an example on http://jsfiddle.net/3sXZw/
Post a Comment for "Simple Percentage Calculation Of An Input Field With Jquery"