Hi all and thanks in advance for your help!
I’m trying to create some custom checkboxes for a contact form. The default checkbox is not visible and is inside a custom checkbox, in the example you’ll understand what I’m looking for. The idea is that once you click on the checkbox, a custom style displays representing that the field has been checked, and if you click again on the same field the style disappears. Right now I’m unable to check, and therefore style, only the selected checbox, instead all the other fields become selected or deselected as well. Another issue is that the checkboxes in the 1st field are checked by default and I need them unchecked.
$('.checkbox input').on( 'click', function() {
if( $(this).is(':checked') ){
$('.checkbox').addClass('checked');
} else {
$('.checkbox').removeClass('checked');
}
});
.checkbox{
width: 125px;
background-color: #fff;
border: 2px solid #1AC4F8;
display: inline-block;
margin: 10px 0;
font-size: 14px;
color: gray;
text-align: center;
cursor: pointer;
-webkit-transition: color 0.8s, background-color 0.8s;
transition: color 0.8s, background-color 0.8s;
}
.checkbox:hover{
color: white;
background-color: #1AC4F8;
}
.checkbox input{
opacity: 0;
position: absolute;
z-index: -1
}
.checkRow{
text-align: center;
}
.checked{
color: white;
background-color: #1AC4F8;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="checkRow">
<label class="checkbox">
<input type="checkbox" name="service" value="SEO">SEO
</label>
<label class="checkbox">
<input type="checkbox" name="service" value="SEM">SEM
</label>
<label class="checkbox">
<input type="checkbox" name="service" value="Emailing">Emailing
</label>
<label class="checkbox">
<input type="checkbox" name="service" value="Social networks">Social networks
</label>
<label class="checkbox">
<input type="checkbox" name="service" value="Web design">Web design
</label>
</div>
I hope everything is clear 🙂
2
Answers
The main problem you’re having is that you are toggling all checkboxes here…
and here
You should be referencing the current element being (un)checked this way…
I just replaced :
$('.checkbox').addClass('checked');
with$(this).parent().addClass('checked');
$('.checkbox').removeClass('checked');
with$(this).parent().removeClass('checked');
I hope that’s what you wanted 🙂