1
\$\begingroup\$
//AMOUNT CALCULATOR
 var totalAmount = 0;
 var serviceAmount = 0;
jQuery('.select-service').click(function(){
 var serviceAmount = parseInt(jQuery(this).parent().html().replace(/\D/g,''));
 if(jQuery(this).is('.selected')){
 jQuery(this).removeClass('selected');
 totalAmount -= serviceAmount;
 jQuery('#total-amount').html(totalAmount);
 }else{
 jQuery(this).addClass('selected');
 totalAmount += serviceAmount;
 jQuery('#total-amount').fadeIn('slow').html(totalAmount);
 }
});
//AMOUNT CALCULATOR

is this code efficient and secure? I am PHP dont know if it is required or not to judge.. Please any Help/feed back would be awesome! really trying to better my coding..

asked Aug 15, 2013 at 19:26
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Security:

If you want to check amounts securely, don't do it in the browser alone: you need a server-side validation (e.g. with PHP if it is your language of choice).

Efficiency:

  1. You can use $('...') instead of jQuery('...') to improve the readability and concision (source: jquery.com).
  2. Avoid looking for divs with jQuery every time you need them by assigning them to a variable. In this case, caching $('#total-amount') seems unnecessary, but it will pay off as soon as you call it once more (see jQuery Best Practices for more information).

Thus:

//AMOUNT CALCULATOR
var totalAmount = serviceAmount = 0;
// caching $('#total-amount')
var totalAmountDiv = $('#total-amount');
$('.select-service').click(function(){
 // caching $(this)
 var thisDiv = $(this);
 var serviceAmount = parseInt(thisDiv.parent().html().replace(/\D/g,''));
 if(thisDiv.is('.selected')){
 thisDiv.removeClass('selected');
 totalAmount -= serviceAmount;
 totalAmountDiv.html(totalAmount);
 }else{
 thisDiv.addClass('selected');
 totalAmount += serviceAmount;
 totalAmountDiv.fadeIn('slow').html(totalAmount);
 }
});
//AMOUNT CALCULATOR
answered Aug 16, 2013 at 8:28
\$\endgroup\$
2
  • \$\begingroup\$ wow thanks man.. but doesnt using jQuery instead of $ prevent conflicts with mootools? \$\endgroup\$ Commented Aug 16, 2013 at 8:30
  • \$\begingroup\$ Yes it does, I just didn't know you used another library. To avoid conflicts, you can also use jQuery.noconflict() or Mootools' Dollar Safe Mode (mootools.net/blog/2009/06/22/the-dollar-safe-mode) \$\endgroup\$ Commented Aug 16, 2013 at 8:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.