ottz0 ottz0 - 27 days ago 12
jQuery Question

Adding and removing classes

I have a

jQuery
Credit Card Plugin and when you enter the credit card number it switches out a class that shows an image for the credit card entered.

How to I clear the credit card each time for the new one to appear?

<div>
<form>
<div id="ccc" class="form-group add-on">
<label for="ccnumber">Credit card Number</label>
<input type="text" class="form-control" id="credit-card" placeholder="Credit Card Number">
</div>
</form>
<div id="output"></div>
<div id="c-card-type"></div>
</div>


JS

if(cardType == null){
return;
}else{
switch(cardType.name){
case 'visa':
$('#output').html('This Card is visa');
$('#c-card-type').toggleClass('c-card vs');
break;
case 'mastercard':
$('#output').html('This Card is mastercard');
$('#c-card-type').toggleClass('c-card mc');
break;
case 'ax':
$('#output').html('This Card is ax');
$('#c-card-type').toggleClass('c-card ax');
break;
default:
$('#output').html('We dont support ' + cardType.name);
}
}

Answer

From your code toggleClass will not work alone, please see the below example of toggleClass

<div id='mydiv' class="class1"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class2"></div>

So you need to remove or empty the class attribute before the if statement or add to each case.

   $('#c-card-type').attr('class','');
or
  $('#c-card-type').removeAttr('class');

now your code should be

$('#c-card-type').attr('class','');
if(cardType == null){
        return;
      }else{
        switch(cardType.name){
          case 'visa':
            $('#output').html('This Card is visa');
          //  $('#c-card-type').attr('class','');
            $('#c-card-type').toggleClass('c-card vs'); 
            break;
          case 'mastercard':
            $('#output').html('This Card is mastercard');  
          //  $('#c-card-type').attr('class','');
            $('#c-card-type').toggleClass('c-card mc'); 
            break;
          case 'ax':
            $('#output').html('This Card is ax');  
          //   $('#c-card-type').attr('class','');
            $('#c-card-type').toggleClass('c-card ax'); 
            break;
          default:
            $('#output').html('We dont support ' + cardType.name);  
        }
      }

I hope this will help you.

Comments