Search code examples
jquerycssarraysstylesheet

Add Css on a Html Class Tag With Jquery


I have a submit button which has a color red css style by default. How can I apply a css styling on it on the fly and seeing the result without refreshing the page using jquery?

I have an oncheck query and I want to put the code that will change styling above the return true;

My button

<input type="submit" name="submit" id="submitForm" class="btn btn-primary-alt" value="Submit" onsubmit="return validate_age();" />

The css styling I want to apply on my submit button

.btn-primary-alt:hover {
background-color: #3b8410;
border-bottom: 3px solid #2a620a;
border-color: #2a620a;
color: #fff;
}

My jquery

if($("#age_18").is(":checked"))
{ 
  // This is where I want the css styling will happen.
  return true;
}
else
{
  alert("You must be above 18 years of age.");
  return false;
}

So basically when my checkbox is checked I want to add a css styling on my submit button. thanks


Solution

  • Best solution would be to create a new class (not :hover). So for example

    .checked{
     background-color: #3b8410;
     border-bottom: 3px solid #2a620a;
     border-color: #2a620a;
     color: #fff;
    }
    

    Then use jQuery to add or remove the class.

    $('#submitForm').addClass('checked');
    

    and

    $('#submitForm').removeClass('checked');