Javascript to add class when checkbox is selected
I have this piece of code:
<div class="quote-box-col14">
<label for="seo" class="quote-service-seo">SEO</label>
<input type="checkbox" name="seo" id="seo" value="Y" class="checkbox-seo" />开发者_运维百科
</div>
Someone can help with a JavaScript that adds class "selected" to when checkbox is selected?
Thanks
This jQuery will do it:
$('#seo').change(function(){
if($(this).is(":checked")) {
$(this).addClass("checked");
} else {
$(this).removeClass("checked");
}
});
See this jQuery fiddle for a working example.
Edit:
If you need it to work in IE too, use the click
event instead:
$('#seo').click(function(){
if($(this).is(":checked")) {
$(this).addClass("checked");
} else {
$(this).removeClass("checked");
}
});
And in pure JavaScript (for HTML5)
document.getElementById ('seo').addEventListener ('click', function (ev) {
ev.target.parentNode.classList[ ev.target.checked ? 'add' : 'remove'] ('selected');
}, false);
There is also a classList.toggle function but there is always a danger that the checkbox and the classList might lose synchronism.
You can infer from this: jQuery toggleClass and check checkbox
But essentially, you can use toggleClass to toggle a specific CSS class:
$("#seo").click(function() {
$(this).toggleClass("cssClassToToggle");
});
Or use addClass to add a new class only:
$("#seo").click(function() {
$(this).addClass("cssClassToToggle");
});
If you are talking a range of checkboxes, you can target with $(":checkbox")
too.
Here's pure js that will work for adding and removing the selected class when any checkbox is checked or unchecked.
Working example: http://jsfiddle.net/S9tSS/
var inputs = document.getElementsByTagName("input");
var checkboxes = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
checkboxes.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
for (var j = 0; j < checkboxes.length; j++) {
checkboxes[j].onclick = function() {
if (this.checked == true) {
this.className += " selected";
} else {
removeClassName(this, 'selected');
}
}
}
function removeClassName(e,t) {
if (typeof e == "string") {
e = xGetElementById(e);
}
var ec = ' ' + e.className.replace(/^\s+|\s+$/g,'') + ' ';
var nc = ec;
if (ec.indexOf(' '+t+' ') != -1) {
nc = ec.replace(' ' + t + ' ',' ');
}
e.className = nc.replace(/^\s+|\s+$/g,'');
return true;
}
Sources: ...well... I would post them, but I'm a new use an can't post more than two links.
With jQuery:
$('input[type="checkbox"]').change(function() {
if (this.checked) {
$(this).addClass('checked');
} else {
$(this).removeClass('checked');
}
});
$('#seo').click(function() {
if (this.checked) {
$(this).addClass('selected');
} else {
$(this).removeClass('selected');
}
});
$('#seo').click(function(){
$(this).toggleClass('selected', this.checked);
});
精彩评论