Reputation: 17
Thanks in advance. I'm so close to getting a label to check a checkbox, using css, boostrap and javascript. The problem is that when clicked THE FIRST TIME, the jquery works but the css doesn't. ONLY after the first time does it work.
html
<label class="checkbox">
<input type="checkbox">
<span class="glyphicon"></span>
</label>
css
label.checkbox input[type="checkbox"] {
display:none;
}
label.checkbox span {
margin:-4px auto;
cursor:pointer;
border:2px solid #BBB;
border-radius:100px;
width:120px;
height:120px;
background:#f33;
position: relative;
transition:background 0.4s;
}
label.checkbox span:before,
label.checkbox :checked + span:after {
position:absolute;
font-size:100px;
top: 8px;
left:8px;
}
label.checkbox span:before {
content: "\e088";
color:#333;
}
label.checkbox :checked + span:before {
visiblity:hidden;
}
label.checkbox span:after {
content:'';
}
label.checkbox :checked + span {
width:120px;
height:120px;
background:#3f3;
}
label.checkbox :checked + span:after {
content: '\e089';
color: #333;
}
jquery
//if checkbox becomes checked
$('label span').on('click', function() {
check = $(this).parent().find('input:checkbox');
//is checked true = uncheck, false = check
(check.prop('checked') ? check.attr('checked', false) : check.attr('checked', true));
});
Upvotes: 0
Views: 394
Reputation: 1413
At the first time, when you click on the label the value of the checkbox is set false so per your ternary operator, it doesn't show changes.
You need to do like this to see changes
$(document).ready(function () {
$('input[type="checkbox"]').on('change', function() {
($(this).is(":checked") ? $(this).attr('checked', true) : $(this).attr('checked', false));
});
});
Here you can see the effect jsfiddle
Upvotes: 3
Reputation: 1580
You can use this javascript
$('label span').on('click', function() {
check = $(this).prev().find('input:checkbox');
//is checked true = uncheck, false = check
(check.prop('checked') ? check.attr('checked', false) : check.attr('checked', true));
});
Upvotes: 0