Javascript to add class when checkbox is selected - javascript

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);
});

Related

dropdown menu dont close after selection

I'm working a simple dropdown menu that changes the options after selecting the provinces to city.
What I want is, to prevent the dropdown to close after choosing the province, but just update the options inside to cities.
I tried this code.
$(document).on('click', '#provinceCity', function (e) {
e.stopPropagation();
});
but doesn't work on me.
here's my code
CODEPEN
function loadProvince(){
$("#provinceCity").html("<option value=''>Select province</option>");
for (var i=0; i<province.length; i++){
$("#provinceCity").append("<option value='"+province[i]["id"]+"'>"+province[i]["name"]+"</option>");
}
}
$(document).ready(function(){
loadProvince();
$("#provinceCity").change(function(){
var selectedText = $("#provinceCity option:selected").text();
if (selectedText != 'Select province') {
if (localStorage.getItem("selectedProvince") === null) {
localStorage.setItem("selectedProvince", selectedText);
}else if (localStorage.getItem("selectedProvince") !== null) {
localStorage.setItem("selectedCity", selectedText);
var selectedProvinceCity = localStorage.getItem("selectedProvince") + "-" + localStorage.getItem("selectedCity");
$('#provinceCity').append($('<option>', {
value: selectedProvinceCity,
text: selectedProvinceCity,
selected: "selected"
}));
setTimeout(function(){
$('#provinceCity').click(function(){
loadProvince();
$(this).unbind('click');
localStorage.removeItem('selectedProvince');
localStorage.removeItem('selectedCity');
})
}, 500);
}
}
for (var i=0; i<province.length; i++){
if ($(this).val() == province[i]["id"]){
$("#provinceCity").empty();
var cities = province[i]["city"];
$("#provinceCity").html("<option value=''>Select city</option>");
for (var j=0; j<cities.length; j++){
$("#provinceCity").append("<option value='"+cities[j]["id"]+"'>"+cities[j]["name"]+"</option>");
}
}
}
});
$( window ).load(function() {
// Run code
localStorage.removeItem('selectedProvince');
localStorage.removeItem('selectedCity');
});
});

After first click of radio button can not fire change event

My jquery change event of radio button not working after first click and does not give any error please help me. i stuck in this from last week.and also cant count proper value because of this problem.
$('input[name="emailing"]').change(function()
{
checkValue();
});
function checkValue(evt) {
alert('hi');
var package = $("#package_value").val();
var emailing = $('input[name="emailing"]:checked').val();
$('input[name="emailing"]').on("mousedown", function() {
var select = $('input[name="emailing"]:checked').val();
$("#selected").val(select);
}).on("mouseup", function() {
$('input[name="emailing"]').prop('checked', false);
$(this).prop('checked', true).checkboxradio("refresh");
});
var selected = $("#selected").val();
alert(selected);
var update = $("#update").val();
if(update != '')
{
var hiddenPackage = $("#hidden_pricing").val();
var hiddenRadion = $("#hidden_radio").val();
var totalValue = package - hiddenRadion;
if(emailing == 1)
{
$("#package_value").val('');
var value = Number(totalValue) + 38;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 2)
{
$("#package_value").val('');
var value = Number(totalValue) + 55;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
if(emailing == 0)
{
$("#package_value").val('');
var value = Number(totalValue) + 0;
$("#package_value").val(value);
$("#hidden_package").val(value);
}
}
}
You should use delegate
$(document).delegate( "input[name='emailing']", "change", function() {
checkValue();
});
Use on() function with any element id instead of (document)
$(document).on('change', 'input[name="emailing"]', function() {
checkValue();
});

Jquery : swap two value and change style

i need to make a script for select a black div by click(go red), and put black div value into a white div value by another click, this is ok but when i try to swap values of two white case, the change do correctly one time, but if i retry to swap two value of white case the values swap correctly but whitout the background color red.
This is my code :
var lastClicked = '';
var lastClicked2 = '';
$(".blackcase").click(function(e) {
var i = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.blackcase').removeClass('red');
if (lastClicked != this.id) {
$(this).addClass('red');
var currentId = $(this).attr('id');
var currentVal = $(this).html();
$(".whitecase").click(function(e) {
$('.blackcase').removeClass('red');
var currentId2 = $(this).attr('id');
if (i <= 0 && $("#" + currentId2).html().length == 0) {
$("#" + currentId2).html(currentVal);
$("#" + currentId).html("");
i = 1;
}
});
} else {
lastClicked = this.id;
}
}
});
$(".whitecase").click(function(e) {
var j = 0;
if ($(this).html().length == 0) {
return false;
} else {
e.preventDefault();
$('.whitecase').removeClass('red');
if (lastClicked2 != this.id) {
$(this).addClass('red');
var currentId0 = $(this).attr('id');
var currentVal0 = $(this).html();
$(".whitecase").click(function(e) {
e.preventDefault();
var currentId02 = $(this).attr('id');
var currentVal02 = $(this).html();
if (j <= 0 && currentVal0 != currentVal02) {
$('.whitecase').removeClass('red');
$("#" + currentId02).html(currentVal0);
$("#" + currentId0).html(currentVal02);
j = 1;
return false;
}
});
} else {
lastClicked2 = this.id;
}
}
});
This is JSfiddle :
https://jsfiddle.net/12gwq95u/12/
Try to take 12 and put into first white case, put 39 into second white case, click on the white case with 12 (go red) then click on the white case with 39, the values swap correctly with the red color when it's select, but if you try to reswap two whitecase values thats work but without the red color.
Thanks a lot
I have spent some time to rewrite your code to make it more clear. I don't know what exactly your code should do but according to the information you have already provided, my version of your code is the following:
var selectedCase = {color: "", id: ""};
function removeSelectionWithRed() {
$('div').removeClass('red');
}
function selectWithRed(element) {
removeSelectionWithRed();
element.addClass('red');
}
function updateSelectedCase(color, id) {
selectedCase.color = color;
selectedCase.id = id;
}
function moveValueFromTo(elemFrom, elemTo) {
elemTo.html(elemFrom.html());
setValueToElem("", elemFrom);
}
function setValueToElem(value, elem) {
elem.html(value);
}
function swapValuesFromTo(elemFrom, elemTo) {
var fromValue = elemFrom.html();
var toValue = elemTo.html();
setValueToElem(fromValue, elemTo);
setValueToElem(toValue, elemFrom);
}
function isSelected(color) {
return selectedCase.color == color;
}
function clearSelectedCase() {
selectedCase.color = "";
selectedCase.id = "";
}
function elemIsEmpty(elem) {
return elem.html().length == 0;
}
$(".blackcase").click(function (e) {
if (elemIsEmpty($(this))) {
return;
}
alert("black is selected");
selectWithRed($(this));
updateSelectedCase("black", $(this).attr("id"), $(this).html());
});
$(".whitecase").click(function (e) {
removeSelectionWithRed();
if (isSelected("black")) {
alert("moving black to white");
moveValueFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
if(isSelected("white") && selectedCase.id !== $(this).attr("id")) {
alert("swap whitecase values");
swapValuesFromTo($("#"+selectedCase.id), $(this));
clearSelectedCase();
return;
}
alert("white is selected");
selectWithRed($(this));
updateSelectedCase("white", $(this).attr("id"), $(this).html());
});
Link to jsfiddle: https://jsfiddle.net/12gwq95u/21/
If my answers were helpful, please up them.
It happens because you have multiple $(".whitecase").click() handlers and they don't override each other but instead they all execute in the order in which they were bound.
I advise you to debug your code in browser console by setting breakpoints in every click() event you have (in browser console you can find your file by navigating to the Sources tab and then (index) file in the first folder in fiddle.jshell.net).
In general I think you should rewrite you code in such a way that you won't have multiple handlers to the same events and you can be absolutely sure what your code does.

suitable substitution in jquery

With the help of jquery I've done the following for changing the color of the row on clicking a checkbox,all the checkbox is having same class name, the code is working fine, but the requirement in one of our project was to do this using simple pure javascript (no library)
can anyone please tell me some solution for this
$(".cbxSelect").click(function (e) {
if (!$(this).closest('tr').hasClass("myclass")) {
$(this).closest('tr').css('background-color', 'yellow');
$(this).closest('tr').addClass("myclass");
} else {
$(this).closest('tr').css('background-color', 'white');
$(this).closest('tr').removeClass("myclass");
}
});
http://jsfiddle.net/Kph8M/8/
var boxes = document.querySelectorAll('.cbxSelect');
for (var i=boxes.length; i--;) {
boxes[i].addEventListener('change', handler, false);
}
function handler() {
var el = this;
while (el.parentNode) {
el = el.parentNode;
if (el.tagName.toLowerCase() === 'tr') {
break;
}
}
if (el.getAttribute('data-color') != 'yellow') {
el.style.backgroundColor = 'yellow';
el.setAttribute('data-color', 'yellow');
}else{
el.style.backgroundColor = 'white';
el.setAttribute('data-color', 'white');
}
}
FIDDLE
Since you already toggle myclass it makes sense to use it for background color:
.myclass {
background: yellow;
}
and JS:
var checks = document.querySelectorAll('.cbxSelect');
for (var i = 0; i < checks.length; i++) {
checks[i].onchange = function() {
var tr = this.parentNode.parentNode;
if (/\bmyclass\b/.test(tr.className)) {
tr.className = tr.className.replace(/\bmyclass\b/g, '');
}
else {
tr.className += ' myclass';
}
};
}
Demo: http://jsfiddle.net/dfsq/Kph8M/12/

jQuery improve table iterator

I have a table containing in every row one cell inside which is checkbox and label for that checkbox.
What I'm trying to do it to hide rows based on inputed text.
Basically this is list on names and I want to filter/hide those that don't contain entered text.
This is my function:
$(function () {
$('#user_name').keyup(function () {
if ($.trim($('input#user_name').val()) == '') {
$('table.myList >tbody >tr').each(function (index, value) {
$(this).css("display", "block");
});
} else {
$('table.myList >tbody >tr').each(function (index, value) {
if ($(this).find('td > label').length > 0) {
if ($(this).find('td > label').html().toLowerCase().indexOf($.trim($('input#user_name').val()).toLowerCase()) >= 0) {
$(this).css("display", "block");
} else {
$(this).css("display", "none");
}
}
});
}
});
});
This code works, if my table has 40 records its fast, but when I increment list to 500 it slows down and crashes my browser after time.
I'm looking for a way to improve this code to work faster.
Here is link to mock-up code: http://jsfiddle.net/gGxcS/
==UPDATE==
Here is my final solution based on answers of #scessor and #nnnnnn:
$(function () {
var $tableRows = $('table.myList tr');
var lastInput = '';
$('#user_name').keyup(function () {
var sValue = $.trim($('input#user_name').val());
if(lastInput==sValue) return;
if (sValue == '') {
$tableRows.show();
} else {
$tableRows.each(function () {
var oLabel = $(this).find('label');
if (oLabel.length > 0) {
if (oLabel.text().toLowerCase().indexOf(sValue.toLowerCase()) >= 0) {
$(this).show();
} else {
$(this).hide();
}
}
});
lastInput=sValue;
}
});
$('img.removeSelections').click(function () {
$('table.myList input[type="checkbox"]').prop("checked", false);
})
});
Can you test this code (with lot of elements)?
$(function () {
$('#user_name').keyup(function () {
var sValue = $.trim($('input#user_name').val());
if (sValue == '') {
$('table.myList tr').show();
} else {
$('table.myList tr').each(function() {
var jThis = $(this);
var oLabel = jThis.find('label');
if (oLabel.length > 0) {
if (oLabel.text().toLowerCase().indexOf(sValue.toLowerCase()) >= 0) {
jThis.show();
} else {
jThis.hide();
}
}
});
}
});
});
Don't call functions with same parameters twice (e.g. $.trim($('input#user_name').val());).
Use short selectors.
Use jquery each only if necessarry (e.g. don't needed here: $('table.myList >tbody >tr').each(function (index, value) {).
=== UPDATE ===
If somebody holds backspace to long, it will set all trs visible again and again. To prevent this you could check, if the last value is equal to the current value. If true, do nothing.
=== UPDATE ===
To uncheck all checkboxes, it depends on your jQuery version.
With jQuery 1.6 and higher:
$('table.myList input[type="checkbox"]').prop("checked", false);
Before:
$('table.myList input[type="checkbox"]').attr("checked", false);
I'd suggest that you cache your jQuery objects - given that you want to process on every keystroke I'd cache the table rows object outside of the keyup handler. Also, don't call functions inside the .each() loop when you can call them once outside - e.g., no need to be calling $.trim($('input#user_name').val()).toLowerCase() on every .each() iteration.
$(function () {
var $tableRows = $('table.myList >tbody >tr');
$('#user_name').keyup(function () {
var searchStr = $.trim($('input#user_name').val()).toLowerCase();
if (searchStr === '') {
$tableRows.css("display", "block");
} else {
$tableRows.each(function (index, value) {
var $this = $(this),
$label =$this.find('td > label');
if ($label.length > 0) {
if ($label.html().toLowerCase().indexOf(searchStr) >= 0) {
$this.css("display", "block");
} else {
$this.css("display", "none");
}
}
});
}
});
});
Demo: http://jsfiddle.net/gGxcS/3/

Categories

Resources