Multiple checkbox filtering with jQuery - javascript

The aim of the code is to use checkboxes for filtering. In the JSFiddle example you can see that there are 5 filter groups with checkboxes.
The goal is: when somebody ticks multiple checkboxes, it should narrow the results list down, no matter if the checked checkboxes are in one filter group or in different groups. For example if you check two boxes in the Filter 1 group (e.g. Check1 and Check2) it should only display those results which are in Check1 AND Check2, which in this case is Result1 only. (Currently the code expands the results and if you check these 2 checkboxes it shows Result1, Result2, Result3 and Result9.)
(The narrowing works if you check checkboxes in different Filter groups and it should remain this way.)
Another goal is that, there are 5 Filter groups, but only the first 3 groups are coded in yet. How can I include the Filter 4 and Filter 5 groups in the code?
Thank you for your help.
The code:
<style media="screen" type="text/css">
body { font-family:'Arial'; color:#646464; }
.filtering-wrap { float:left; width:20%; margin:0 5% 0 0; padding:0; position:relative;}
</style>
<script type="text/javascript" src="/javascript/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
var byFilter1 = [], byFilter2 = [], byFilter3 = [], byFilter4 = [], byFilter5 = [];
$("input[name=fl-1]").on( "change", function() {
if (this.checked) byFilter1.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter1, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-2]").on( "change", function() {
if (this.checked) byFilter2.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter2, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-3]").on( "change", function() {
if (this.checked) byFilter3.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter3, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-4]").on( "change", function() {
if (this.checked) byFilter4.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter4, "[data-category~='" + $(this).attr("value") + "']");
});
$("input[name=fl-5]").on( "change", function() {
if (this.checked) byFilter5.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byFilter5, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.results > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byFilter1.length) {
if (str == "Include items \n") {
str += " " + "with (" + byFilter1.join(',') + ")\n";
$($('input[name=fl-1]:checked')).each(function(index, byFilter1){
if(selector === '') {
selector += "[data-category~='" + byFilter1.id + "']";
} else {
selector += ",[data-category~='" + byFilter1.id + "']";
}
});
} else {
str += " AND " + "with (" + byFilter1.join(' OR ') + ")\n";
$($('input[name=fl-2]:checked')).each(function(index, byFilter1){
selector += "[data-category~='" + byFilter1.id + "']";
});
}
}
if (byFilter2.length) {
if (str == "Include items \n") {
str += " " + "with (" + byFilter2.join(' OR ') + ")\n";
$($('input[name=fl-2]:checked')).each(function(index, byFilter2){
if(selector === '') {
selector += "[data-category~='" + byFilter2.id + "']";
} else {
selector += ",[data-category~='" + byFilter2.id + "']";
}
});
} else {
str += " AND " + "with (" + byFilter2.join(' OR ') + ")\n";
$($('input[name=fl-2]:checked')).each(function(index, byFilter2){
if(cselector === '') {
cselector += "[data-category~='" + byFilter2.id + "']";
} else {
cselector += ",[data-category~='" + byFilter2.id + "']";
}
});
}
}
if (byFilter3.length) {
if (str == "Include items \n") {
str += " " + "with (" + byFilter3.join(' OR ') + ")\n";
$($('input[name=fl-3]:checked')).each(function(index, byFilter3){
if(selector === '') {
selector += "[data-category~='" + byFilter3.id + "']";
} else {
selector += ",[data-category~='" + byFilter3.id + "']";
}
});
} else {
str += " AND " + "with (" + byFilter3.join(' OR ') + ")\n";
$($('input[name=fl-3]:checked')).each(function(index, byFilter3){
if(nselector === '') {
nselector += "[data-category~='" + byFilter3.id + "']";
} else {
nselector += ",[data-category~='" + byFilter3.id + "']";
}
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.results > div').filter(selector).show();
} else if (cselector === '') {
$('.results > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.results > div').filter(selector).filter(cselector).show();
} else {
$('.results > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
});
</script>
<div class="filtering-wrap">
<p style="font-size:12px;"><strong>Filter 1</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-1" value="check1" id="check1" /> Check1</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-1" value="check2" id="check2" /> Check2</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-1" value="check3" id="check3" /> Check3</label><br>
</form>
<p style="font-size:12px;"><strong>Filter 2</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check4" id="check4" /> Check4</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check5" id="check5" /> Check5</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check6" id="check6" /> Check6</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check7" id="check7" /> Check7</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check8" id="check8" /> Check8</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-2" value="check9" id="check9" /> Check9</label>
</form>
<p style="font-size:12px;"><strong>Filter 3</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-3" value="check10" id="check10" /> Check10</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-3" value="check11" id="check11" /> Check11</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-3" value="check12" id="check12" /> Check12</label>
</form>
<p style="font-size:12px;"><strong>Filter 4</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check13" id="check13" /> Check13</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check14" id="check14" /> Check14</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check15" id="check15" /> Check15</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check16" id="check16" /> Check16</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-4" value="check17" id="check17" /> Check17</label>
</form>
<p style="font-size:12px;"><strong>Filter 5</strong></p>
<form>
<label style="font-size:12px;"><input type="checkbox" name="fl-5" value="check18" id="check18" /> Check18</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-5" value="check19" id="check19" /> Check19</label><br>
<label style="font-size:12px;"><input type="checkbox" name="fl-5" value="check20" id="check20" /> Check20</label>
</div>
<div class="results">
<div class="result" data-id="result1" data-category="check1 check2 check3 check4 check5 check6 check7 check8 check9 check10">Result1</div>
<div class="result" data-id="result2" data-category="check1 check3 check5 check7 check9 check11 check13 check15 check17 check19">Result2</div>
<div class="result" data-id="result3" data-category="check2 check4 check6 check8 check10 check12 check14 check16 check18 check20">Result3</div>
<div class="result" data-id="result4" data-category="check5 check6 check7 check8 check9 check10">Result4</div>
<div class="result" data-id="result5" data-category="check15">Result5</div>
<div class="result" data-id="result6" data-category="check3 check13 check20">Result6</div>
<div class="result" data-id="result7" data-category="check11 check12 check13 check14 check15 check16">Result7</div>
<div class="result" data-id="result8" data-category="check4 check8 check12 check16 check20">Result8</div>
<div class="result" data-id="result9" data-category="check2 check3 check5 check7 check11 check13 check17 check19">Result9</div>
<div class="result" data-id="result10" data-category="check3 check6 check9 check12 check15 check18">Result10</div>
<div class="result" data-id="result11" data-category="check5 check10 check15 check20">Result11</div>
<div class="result" data-id="result12" data-category="check6 check12 check18">Result12</div>
<div class="result" data-id="result13" data-category="check7 check14">Result13</div>
<div class="result" data-id="result14" data-category="check8 check16">Result14</div>

You can do all groups and use a simpler process to do it by using filter() and creating a simpler set of data arrays for comparisons.
var $results=$('.result'),
$checks=$(':checkbox[name^=fl]');
$checks.change(function(){
var $checked=$checks.filter(':checked');
/* show all when nothing checked*/
if(!$checked.length){
$results.show();
return; /* quit here if nothing checked */
}
/* create array of checked values */
var checkedVals= $.map($checked, function(el){
return el.value
});
/* hide all results, then filter for matches */
$results.hide().filter(function(){
/* split categories for this result into an array*/
var cats=$(this).data('category').split(' ');
/* filter the checkedVals array to only values that match */
var checkMatches=$.grep(checkedVals, function(val){
return $.inArray(val, cats) >-1;
});
/* only return elements with matched array and original array being same length */
return checkMatches.length === checkedVals.length;
/* show results that match all the checked checkboxes */
}).show();
/* do something when there aren't any matches */
if(!$results.length){
alert('Ooops...no matches');
}
});
DEMO

Related

How can I check the array of radio name button if it is not checked

Hi I have dynamice adding of radio button and this radio button is array named
I want to make sure that the user selected 1 radio button in each radio array
Thank you in advance
$(function() {
function addMore() {
for (var i = 0; i < dynamic_range; i++) {
$('.container_div').append(
'<div class="form-group">' +
'<div class="input-group">' +
'<ul>' +
'<li><input type="radio" name="playergroup' + i + '[]" class="form-control"></li>' +
'<li><input type="radio" name="playergroup' + i + '[]" class="form-control"></li>' +
'<li><input type="radio" name="playergroup' + i + '[]" class="form-control"></li>' +
'<li><input type="radio" name="playergroup' + i + '[]" class="form-control"></li>' +
'</ul>' +
'</div>' +
'</div>'
);
}
}
$('#save').on('click', function(e) {
e.preventDefault();
for (var i = 0; i < dynamic_range; i++) {
if (!$("input[name='playergroup[i]']:checked").val()) {
console.log("radio group is not check");
return false;
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<div class="container_div"></div>
<button id="save">Save</save>
</form>
You html and jquery does not match.
html: <input type="radio" name="playergroup'+i+'[]" class="form-control">
jquery is looking for: name='playergroup[i]' but i is not inside the [] in your html
Solution : $("input[name*='playergroup" + i + "']:checked");
Demo*
$(function() {
function addMore() {
for (var i = 0; i < 2; i++) {
$('.container_div').append(
'<div class="form-group">' +
'<div class="input-group">' +
'<ul>' +
'<li><input type="radio" name="playergroup' + i + '[]" class="form-control"></li>' +
'<li><input type="radio" name="playergroup' + i + '[]" class="form-control"></li>' +
'<li><input type="radio" name="playergroup' + i + '[]" class="form-control"></li>' +
'<li><input type="radio" name="playergroup' + i + '[]" class="form-control"></li>' +
'</ul>' +
'</div>' +
'</div>'
);
}
}
addMore()
$('#save').on('click', function(e) {
e.preventDefault();
for (var i = 0; i < 2; i++) {
if (!$("input[name*='playergroup" + i + "']:checked").val()) {
console.log("radio group is not check");
return false;
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<div class="container_div"></div>
<button id="save">Save</save>
</form>

Limit number of javascript automated generated checkbox

kinda worried with following code that should automatically generate checkbox content AND limit up to 3 the number of checked boxes.
Separately both codes work fine, the issue occurs when they are combined:
Fiddle
$('input[type=checkbox]').change(function(e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
}
})
var skills = ["centres", "tirs", "dribbles", "passes", "vitesse"]
var skillContainer = $("#skillsContainer");
skills.forEach(skill => skillContainer.append('<li> <input type=\"checkbox\" id=\"' + skill + '\" value=\"' + skill + '\"> <label for=\"' + skill + '\"> ' + skill + ' </label> </li>'));
$("#skillsContainer").append(checkboxElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="competencies" action="algo.php" method="POST">
<div class="container">
<ul class="ks-cboxtags" id="skillsContainer">
<input class="button" type="submit" value="Valider">
</ul>
</div>
</form>
You mean this?
You need to delegate when you create dynamic elements
OR add the event handler after the generation
$('#skillsContainer').on("change", 'input[type=checkbox]', function(e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
}
})
var skills = ["centres", "tirs", "dribbles", "passes", "vitesse"]
$("#skillsContainer").html(skills.map(skill => '<li> <input type=\"checkbox\" id=\"' + skill + '\" value=\"' + skill + '\"> <label for=\"' + skill + '\"> ' + skill + ' </label> </li>').join(""));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="competencies" action="algo.php" method="POST">
<div class="container">
<ul class="ks-cboxtags" id="skillsContainer">
<input class="button" type="submit" value="Valider">
</ul>
</div>
</form>
Pure javascript to check checked checkbox length
var eLength = element.length;
var i = 0;
var checkedCheck;
checkbox.forEach(checkBox => {
checkBox.addEventListener('click',function(){
if(this.checked){
i++;
if(i > 3){
checkBox.disabled = true;
alert('Limit reached');
}
}
});
});

Multiple Checkboxes with Select All

I modified an existing fiddle to get a comprehensive solution for multiple checkboxes with select/unselect functionality. Now, it counts how many checkboxes checked and also gives which the checkboxes checked. It looks like it works fine but there are some points to fix and needs to improve it a bit more:
When you first check the option A and then click the "Select All" checkbox, the system does not work well.
The whole code looks like it's a bit long. I think we can shorten the code someway but I don't know how.
When we check all options manually, the firstgroup checkbox should automatically be checked or otherwise when any of the options are unchecked, the firstgroup checkbox should automatically unchecked. And accordingly, the div contents should change.
Thanks for any contribution.
<div style="margin-left: 20px;">
<input type="checkbox" id="firstgroup" /> Select All<br>
<input type="checkbox" class="order" id="first" /> A<br>
<input type="checkbox" class="order" id="second" /> B<br>
<input type="checkbox" class="order" id="third" /> C
</div>
<div id="result"></div>
<div id="form">Lorem ipsum</div>
x = document.getElementById("result");
y = document.getElementById("form");
x.innerHTML = '';
y.innerHTML = '';
$("#firstgroup").click(function() {
var checkBoxes = $("input[type='checkbox'].order");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
$("input[type='checkbox'].order").change(function() {
var check = $("input[type='checkbox'].order:checked").length;
var tnocb = $("input[type='checkbox'].order").length;
var classes = $("input[type='checkbox'].order:checked").map(function() {
return this.id;
}).get().join(", ");
if(check > 0) {
if(check == 1) {
x.innerHTML = 'Checked Checkbox: ' + classes + '<br>Total number of checked checkbox: ' + check;
} else if(check == tnocb) {
x.innerHTML = 'all of them are checked';
} else {
x.innerHTML = 'Checked Checkboxes: ' + classes + '<br>Total number of checked checkboxes: ' + check;
}
y.style.display = 'block';
} else {
x.innerHTML = '';
y.style.display = 'none';
}
return false;
});
$("#firstgroup").click(function() {
$('#form').text('');
$('#result').text('');
$('input:checkbox').not(this).prop('checked', this.checked);
if ($(".order:checked").length == 3) {
$('#form').text('all of them are checked');
}
});
$(".order").on('click', function() {
var selectedItems = '';
$('#result').text('');
$('#form').text('');
if ($(".order:checked").length == 3) {
$('#form').text('all of them are checked');
$("#firstgroup").prop('checked','checked');
} else if ($(".order:checked").length > 0) {
$("#firstgroup").prop('checked','');
$(".order:checked").each(function(i, d) {
selectedItems += d.id + ',';
});
$('#result').text('Checked Checkboxes: ' + selectedItems.substring(0, selectedItems.length - 1));
$('#form').text('Total number of checked checkboxes: ' + $(".order:checked").length);
}
});
<div style="margin-left: 20px;">
<input type="checkbox" id="firstgroup" /> Select All<br>
<input type="checkbox" class="order" id="first" /> A<br>
<input type="checkbox" class="order" id="second" /> B<br>
<input type="checkbox" class="order" id="third" /> C
</div>
<div id="result"></div>
<div id="form"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
The first issue
$("#firstgroup").click(function() {
var checkBoxes = $("input[type='checkbox'].order");
checkBoxes.prop("checked", $("#firstgroup").prop("checked"));
});
The second issue I can not fix.
$("#firstgroup").click(function () {
if ($("#firstgroup[type='checkbox']:checked"));
{
$("#firstgroup").siblings("input[type='checkbox']").prop('checked', true);
}
});
maybe it helps you.
<div style="margin-left: 20px;">
<input type="checkbox" id="firstgroup" /> Select All<br>
<input type="checkbox" class="order" id="first" /> A<br>
<input type="checkbox" class="order" id="second" /> B<br>
<input type="checkbox" class="order" id="third" /> C
</div>
<div id="result"></div>
<div id="form">Lorem ipsum</div>
<script type="text/javascript">
x = document.getElementById("result");
y = document.getElementById("form");
x.innerHTML = '';
y.innerHTML = '';
$("#firstgroup").click(function() {
var checkBoxes = $("input[type='checkbox'].order");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
$('.order').not(this).prop('checked', this.checked); //it will check and uncheck all checkbox
});
$("input[type='checkbox'].order").change(function() {
var check = $("input[type='checkbox'].order:checked").length;
var tnocb = $("input[type='checkbox'].order").length;
var classes = $("input[type='checkbox'].order:checked").map(function() {
return this.id;
}).get().join(", ");
if(check > 0) {
if(check == 1) {
x.innerHTML = 'Checked Checkbox: ' + classes + '<br>Total number of checked checkbox: ' + check;
} else if(check == tnocb) {
x.innerHTML = 'all of them are checked';
} else {
x.innerHTML = 'Checked Checkboxes: ' + classes + '<br>Total number of checked checkboxes: ' + check;
}
y.style.display = 'block';
} else {
x.innerHTML = '';
y.style.display = 'none';
}
return false;
});
</script>
I updated the multiple checkboxes with Select All's code: http://jsfiddle.net/LUtJF/42/
Now, you can
Get the number of checked checkboxes
Get the labels of the checked checkboxes
Get a message when all the checkboxes are checked
When you select all the checkboxes, the "Select All" checkbox is also checked automatically, or vice versa.
The system is responsive. Whenever you add a new option, no need to change any code.
Thanks for all your contribution and hope you'll find this last version useful.
Ahmet Arduc
www.ahmath.com
<div style="margin-left: 20px;">
<input type="checkbox" id="firstgroup" /> Select All<br>
<input type="checkbox" class="order" id="first" /> A<br>
<input type="checkbox" class="order" id="second" /> B<br>
<input type="checkbox" class="order" id="third" /> C<br>
<input type="checkbox" class="order" id="forth" /> D
</div>
<div id="result"></div>
<div id="form"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
$("#firstgroup").click(function() {
$('#form').text('');
$('#result').text('');
$('input:checkbox').not(this).prop('checked', this.checked);
if($(".order:checked").length == $(".order").length) {
$('#form').text('all of them are checked');
}
});
$(".order").on('click', function() {
var selectedItems = '';
$('#result').text('');
$('#form').text('');
if ($(".order:checked").length == $(".order").length) {
$('#firstgroup').prop('checked', true);
$('#form').text('all of them are checked');
} else if ($(".order:checked").length > 0) {
$('#firstgroup').prop('checked', false);
$(".order:checked").each(function(i, d) {
selectedItems += d.id + ',';
});
$('#result').text('Checked Checkboxes: ' + selectedItems.substring(0, selectedItems.length - 1));
$('#form').text('Total number of checked checkboxes: ' + $(".order:checked").length);
}
});

Change input type, from radio button to checkbox, jquery

First of this is my very first jQuery script if you have any suggestions don’t be shy.
I'm trying to do the following. I have 3 columns of radio buttons. With a checkbox above. When I check one of those checkboxes the column changes from radio button to checkboxes and there can only be changed one row at the time. My script is doing all that, but I have one problem. When I change the type, all inputs get the same attribute of the first input. I think I should have some sort of loop but I have absolutely no idea how to do this.
So, my question: how can I change my script so that just the type change and not the other attributes?
https://jsfiddle.net/bjc3a9y7/1/
$('input[name="switch"]').change(function() {
var checked = $(this).is(':checked');
$('input[name="switch"]').prop('checked',false);
var brandType = $('input[name="brand"]').prop("type");
var fuelType = $('input[name="fuel"]').prop("type");
var bodyType = $('input[name="body"]').prop("type");
if (brandType == 'checkbox') {
var oldInput = $('input[name="brand"]');
$('input[name="brand"]').replaceWith(
$('<input type="radio" />').
attr("value", oldInput.attr("value")).
attr("name", oldInput.attr("name")).
attr("id", oldInput.attr("id"))
)
} else if (fuelType == 'checkbox') {
var oldInput = $('input[name="fuel"]');
$('input[name="fuel"]').replaceWith(
$('<input type="radio" />').
attr("value", oldInput.attr("value")).
attr("name", oldInput.attr("name")).
attr("id", oldInput.attr("id"))
)
} else if (bodyType == 'checkbox') {
var oldInput = $('input[name="body"]');
$('input[name="body"]').replaceWith(
$('<input type="radio" />').
attr("value", oldInput.attr("value")).
attr("name", oldInput.attr("name")).
attr("id", oldInput.attr("id"))
)
};
if(checked) {
$(this).prop('checked',true);
var id = $(this).attr("id");
var oldInput = $('input[name="' + id + '"]');
$('input[name="' + id + '"]').replaceWith(
$('<input type="checkbox" />').
attr("value", oldInput.attr("value")).
attr("name", oldInput.attr("name")).
attr("id", oldInput.attr("id"))
)
};
});
#container {
display: flex;
flex-direction: row;
}
.filter {
width: 150px;
display: flex;
flex-direction: column;
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<div id='container'>
<div class='filter'>
<header>
Brand <input type='checkbox' id='brand' name='switch' class='switch'>
</header>
<div id='brand'>
<div class='filter-item'>
<span><input type='radio' id='mercedes' name='brand' value='mercedes'></span>
<label for='mercedes'><span></span>Mercedes-benz</label>
</div>
<div class='filter-item'>
<input type='radio' id='bmw' name='brand' class='brand' value='bmw'>
<label for='bmw'><span></span>BMW</label>
</div>
<div class='filter-item'>
<input type='radio' id='audi' name='brand' class='brand' value='audi'>
<label for='audi'><span></span>Audi</label>
</div>
<div class='filter-item'>
<input type='radio' id='ford' name='brand' class='brand' value='ford'>
<label for='ford'><span></span>Ford</label>
</div>
<div class='filter-item'>
<input type='radio' id='dodge' name='brand' class='brand' value='dodge'>
<label for='dodge'><span></span>Dodge</label>
</div>
</div>
</div>
<div class='filter'>
<header>
Fuel <input type='checkbox' id='fuel' name='switch' class='switch'>
</header>
<div class='filter-item'>
<input type='radio' id='diesel' name='fuel' class='fuel' value='diesel'>
<label for='diesel'><span></span>Diesel</label>
</div>
<div class='filter-item'>
<input type='radio' id='gasoline' name='fuel' class='fuel' value='gasoline'>
<label for='gasoline'><span></span>Gasoline</label>
</div>
<div class='filter-item'>
<input type='radio' id='electric' name='fuel' class='fuel' value='electric'>
<label for='electric'><span></span>Electric</label>
</div>
<div class='filter-item'>
<input type='radio' id='other' name='fuel' class='fuel' value='other'>
<label for='other'><span></span>Other</label>
</div>
</div>
<div class='filter'>
<header>
Body <input type='checkbox' id='body' name='switch' class='switch'>
</header>
<div class='filter-item'>
<input type='radio' id='convertible' name='body' class='body' value='convertible'>
<label for='convertible'><span></span>Convertible</label>
</div>
<div class='filter-item'>
<input type='radio' id='coupe' name='body' class='body' value='coupe'>
<label for='coupe'><span></span>Coupe</label>
</div>
<div class='filter-item'>
<input type='radio' id='sedan' name='body' class='body' value='sedan'>
<label for='sedan'><span></span>Sedan</label>
</div>
<div class='filter-item'>
<input type='radio' id='station' name='body' class='body' value='station'>
<label for='station'><span></span>Station wagon</label>
</div>
</div>
</div>
Well I didn't stop trying and finally I got it to work with .each() loops. I added a checkbox selection limitation of 2 as well. I'm new to JQuery so maybe the code isn't as clean as I would like, but it seems to work perfectly.
https://jsfiddle.net/bjc3a9y7/2/
$('input[name="switch"]').change(function() {
var checked = $(this).is(':checked');
$('input[name="switch"]').prop('checked',false);
var arr = ["brand", "fuel", "body"];
$.each( arr, function( i, val ) {
var type = $('input[name="' + val + '"]').prop("type");
if (type == 'checkbox') {
$('input[name="' + val + '"]').each(function(index, value){
var oldInput = $(value);
if(index == 0){
$(value).replaceWith(
$('<input type="radio" />').
prop("value", oldInput.prop("value")).
prop("name", oldInput.prop("name")).
prop("id", oldInput.prop("id")).
prop('checked',true)
)
} else {
$(value).replaceWith(
$('<input type="radio" />').
prop("value", oldInput.prop("value")).
prop("name", oldInput.prop("name")).
prop("id", oldInput.prop("id"))
)
}
});
};
});
if(checked) {
$(this).prop('checked',true);
var id = $(this).prop("id");
$('input[name="' + id + '"]').each(function(index, value){
var oldInput = $(value);
var checked2 = $(value).is(':checked');
if(checked2) {
$(value).replaceWith(
$('<input type="checkbox" />').
prop("value", oldInput.prop("value")).
prop("name", oldInput.prop("name")).
prop("id", oldInput.prop("id")).
prop('checked',true)
)
}else{
$(value).replaceWith(
$('<input type="checkbox" />').
prop("value", oldInput.prop("value")).
prop("name", oldInput.prop("name")).
prop("id", oldInput.prop("id"))
)
}
});
// limit selection checkboxes
$('input[name="' + id + '"]').change(function(){
var max= 2;
if( $('input[name="' + id + '"]:checked').length == max ){
$('input[name="' + id + '"]').prop('disabled', 'disabled');
$('input[name="' + id + '"]:checked').removeProp('disabled');
}else{
$('input[name="' + id + '"]').removeProp('disabled');
}
});
}
});

How to check if checkbox is checked without using getElementBy "id" or "name" attr?

I work with IE8 ONLY.
I have multiple check boxes , so i cannot write a separate onchange function for each .
Here is what i tried to do
HTML
<input checked type='checkbox' id='check1' onchange = 'checkChange()'>Ch1</input>
<input checked type='checkbox' id='check2' onchange = 'checkChange()'>Ch2</input>
<input checked type='checkbox' id='check3' onchange = 'checkChange()'>Ch3</input>
JS
function checkChange() {
if ($(this).is(':checked')) {
alert("Box " + $(this).id + " is checked");
}
else {
alert("Box " + $(this).id + " is unchecked");
}
}
It does not work properly. How can I get an alert message showing checkbox id that was checked or unchecked
Thanks
this is not related to the element which raised the event when using an on* handler, you need to pass it as a parameter:
<input checked="checked" type="checkbox" id="check1" onchange="checkChange(this)">Ch1
<input checked="checked" type="checkbox" id="check2" onchange="checkChange(this)">Ch2
<input checked="checked" type="checkbox" id="check3" onchange="checkChange(this)">Ch3
Then you can use it in your JS code:
function checkChange(that) {
if ($(that).is(':checked')) {
alert("Box " + that.id + " is checked");
}
else {
alert("Box " + that.id + " is unchecked");
}
}
You could also cut out the ugly attributes and use a pure jQuery implementation:
<input checked="checked" type="checkbox" id="check1" class="check">Ch1
<input checked="checked" type="checkbox" id="check2" class="check">Ch2
<input checked="checked" type="checkbox" id="check3" class="check">Ch3
$(function() {
$('.check').change(function() {
var state = this.checked ? "checked" : "unchecked";
alert("Box " + this.id + " is " + state);
});
});
try this:
<input checked type='checkbox' id='check1' onchange='checkChange(this)'>Ch1</input>
function checkChange(cbox) {
if (cbox.checked == true) {
....
Don't use onchange attributes. Bind the event with JavaScript (jQuery). You can add a class to all the checkboxes to bind to all of them at once:
<input checked type='checkbox' id='check1' class='checkChange'>Ch1
<input checked type='checkbox' id='check2' class='checkChange'>Ch2
<input checked type='checkbox' id='check3' class='checkChange'>Ch3
<script>
$(function(){
$('.checkChange').change(function(){
if ($(this).is(':checked')) {
alert("Box " + this.id + " is checked");
}
else {
alert("Box " + this.id + " is unchecked");
}
});
});
</script>
Note that $(this).id is invalid. It should be this.id or $(this).prop('id'). Also, don't use </input>. There is no closing tag for inputs.
Use a class:
function checkChange() {
if ($(this).is(':checked')) {
alert("Box " + this.id + " is checked");
}
else {
alert("Box " + this.id + " is unchecked");
}
}
$(".check").on("click",checkChange)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input checked type='checkbox' id='check1' class=check >Ch1</input>
<input checked type='checkbox' id='check2' class=check >Ch2</input>
<input checked type='checkbox' id='check3' class=check >Ch3</input>
If you don't want to use class you can select inputs based on the beginning of the id [id^=check]
function checkChange() {
if ($(this).is(':checked')) {
alert("Box " + this.id + " is checked");
}
else {
alert("Box " + this.id + " is unchecked");
}
}
$("[id^=check]").on("click",checkChange)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=checkbox id=check1 checked>Ch1</input>
<input type=checkbox id=check2 checked>Ch2</input>
<input type=checkbox id=check3 checked>Ch3</input>
$('input[type="checkbox"]').on('change', function(){
if ($(this).is(':checked')) {
alert("Box " + $(this).id + " is checked");
}
else {
alert("Box " + $(this).id + " is unchecked");
}
}
Pass a reference to self, then you can do whatever you want with it.
<input checked="" type="checkbox" id="check1" onchange="checkChange(this)">Ch1
<input checked="" type="checkbox" id="check2" onchange="checkChange(this)">Ch2
<input checked="" type="checkbox" id="check3" onchange="checkChange(this)">Ch3
function checkChange(bx){ console.log(bx) }

Categories

Resources