3
\$\begingroup\$

I feel like I should not be duplicating the code to gather the credit card number, but I am not sure how best to do it. Any suggestions?

$('input[name="payment\[cc_number\]"]').keyup(function() {
    var ccNum = $(this).val();
    ccNum = ccNum.replace(/[^\d]/g, '');
    setSelectValue(ccNum);
});

$('input[name="payment\[cc_number\]"]').blur(function(ccNum) {
    var ccNum = $(this).val();
    ccNum = ccNum.replace(/[^\d]/g, '');
    if (!luhnCheck(ccNum)) {
        alert('Please enter a valid credit card number.');
    }
});
\$\endgroup\$
  • 1
    \$\begingroup\$ There is a nice jQuery plugin to handle credit card validation which might be easier than writing your own. \$\endgroup\$ – James Allardice Jun 13 '12 at 13:36
2
\$\begingroup\$
$(function() {
  // Always select a context and use it as the second parameter 
  // it will make everything far faster and less prone to errors
  var form = $('form'); 
  var stripCcNum = function(el) {
      return $(this).val().replace(/[^\d]/g, '');
  }

  $('input[name="payment\[cc_number\]"]', form).keyup(function() {

    setSelectValue(stripCcNum(this));

  }).blur(function(ccNum) {

    if (!luhnCheck( stripCcNum(this) )) {
        alert('Please enter a valid credit card number.');
    }

  });

});

Or for the totally and absolute 1337 (meaning you shouldn't do it for something this simple but it demonstrates some useful techniques)

$(function() {
  var form = $('form'),
    handleCcNum = function(doThis) {
      return function() { 
        doThis.call(this, $(this).val().replace(/[^\d]/g, ''));
      }
    }

  $('input[name="payment\[cc_number\]"]', form)
    .keyup( handleCcNum(function(num) { setSelectValue(num); } )
    .blur( handleCcNum(function(num) { 
       !luhnCheck(num) && alert('Please enter a valid credit card number.');
    }));
});
\$\endgroup\$
  • 2
    \$\begingroup\$ I would use jQuery 1.7's .on: $("foo").on({keyup: handleCcNum(...), blur: handleCcCum(...)};. \$\endgroup\$ – ANeves Jun 13 '12 at 17:20
  • \$\begingroup\$ Nice @ANeves - didn't know about that syntax \$\endgroup\$ – George Mauer Jun 13 '12 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.