JS / jQuery - Filtering divs with checkboxes - javascript

I'm trying to filter some divs with checkboxes using the following code:
$("#filterControls :checkbox").click(function() {
$(".sectionContent").hide();
$("#filterControls :checkbox:checked").each(function() {
$("." + $(this).val()).show();
});
if($("#filterControls :checkbox").prop('checked') == false){
$(".sectionContent").show();
}
});
This works fine when you check the first checkbox, but it only filters with the others when you also have the first checkbox selected. It's hard to explain but try the JSFiddle: http://jsfiddle.net/BY9JL/
I don't want it to rely on having the first checkbox checked, is there a way around this?

Try
var sections = $('.sectionContent');
function updateContentVisibility(){
var checked = $("#filterControls :checkbox:checked");
if(checked.length){
sections.hide();
checked.each(function(){
$("." + $(this).val()).show();
});
} else {
sections.show();
}
}
$("#filterControls :checkbox").click(updateContentVisibility);
updateContentVisibility();
Demo: Fiddle

It's because your last if check, it will only check the first checkbox if it is checked or not.
You could change your last if block to see if there are any checked at all:
if($("#filterControls :checkbox:checked").length == 0){
$(".sectionContent").show();
}

Related

Uncheck a Checkbox using Jquery

I have a page with a list of check boxes, when a check box is checked I am updating the number of check boxes selected in side a p tag. This is all working.
The problem I have is when the user selects more than 5 checkboxes I want to use Jquery to unselect it.
This is what I have so far, the first if else works but the first part of the if doe
$("input").click(function () {
if ($("input:checked").size() > 5) {
this.attr('checked', false) // Unchecks it
}
else {
$("#numberOfSelectedOptions").html("Selected: " + $("input:checked").size());
}
});
Any ideas?
Firstly you should use the change event when dealing with checkboxes so that it caters for users who navigate via the keyboard only. Secondly, if the number of selected checkboxes is already 5 or greater you can stop the selection of the current checkbox by using preventDefault(). Try this:
$("input").change(function (e) {
var $inputs = $('input:checked');
if ($inputs.length > 5 && this.checked) {
this.checked = false;
e.preventDefault();
} else {
$("#numberOfSelectedOptions").html("Selected: " + $inputs.length);
}
});
Example fiddle
Note I restricted the fiddle to 2 selections so that it's easier to test.
You need this $(this).prop('checked', false);
You should be saying
$(this).attr('checked', false)
instead of
this.attr('checked', false)
You need this $(this).prop('checked', false);
Also this is a javascript object, if you want to use jquery you should prefer $(this).

Dynamically Uncheck All Checkbox's From Container Using A Textbox

fiddle - http://jsbin.com/OruFonU/1/edit
completed fiddle (for anyone who's in the same boat) - http://jsbin.com/OruFonU/15/edit
I'm trying to uncheck all checkbox's based upon the text in a texbox. If the textbox's value is equal to "Uncheck All" I want all checkbox's unchecked inside it's container div. (not all completely, just all inside the visible container)
I've tried the following but no luck.
.removeAttr('checked');
.attr('checked', false);
.prop('checked', false);
.is(':checked', false);
Here's the full JQuery/Javascript
$(document).ready(function() {
$('input[type=checkbox]').prop('checked', 'checked');
$('.show').hide();
$('.number-1').show();
$(".show-nums").on('load change', function() {
var val = $(this).val().toLowerCase();
if( $("." + val) && $("." + val).length ){
//check if there is a selector that corresponds to the value of the dropdown
$('.show').hide();
$("." + val).show();
}
});
$(".search").on('keyup change', function() {
var val = $(this).val();
if(val === "Uncheck All") {
$('.number-1 input[type=checkbox], .number-2 input[type=checkbox], .number-3 input[type=checkbox], .number-4 input[type=checkbox]').prop('checked', false);
}
});
});
If anyone can help me with this it'd be greatly appreciated.
It's because you wrap form inside p tag. Try to put your form inside div and it should work as expected
Demo
Basically your code would work. The thing that fails is the the selector for the inputs. You can fix that by fixing the selector for example juste use input[type=text].
There are other things you could improve, I have updated your jsbin:
http://jsbin.com/OruFonU/13/edit
you can dramatically simplify your code (and make it more readable) by doing this:
$(".show-nums").on('load change', function() {
var val = $(this).val();
$('.show').hide();
if( $("." + val) && $("." + val).length ){
//check if there is a selector that corresponds to the value of the dropdown
$("." + val).show();
}
});
side note: form tags are not allowed inside of paragraphs (p). Since inline elements are not allowed inside a p elements, the browser just assumes that the p tag was not closed and close it by him self. This is the result, and this is why your selector is not working:
The forms are not inside the P elements anymore.
If you have to stick to your HTML structure I would suggest you set the .number-n on the form tag.
you problem is that this selector:
$('.number-1 input[type=checkbox], .number-2 input[type=checkbox], .number-3 input[type=checkbox], .number-4 input[type=checkbox]')
returns [] empty.
just use $('input:checkbox').removeAttr('checked');
$(".search").on('keyup change', function() {
var val = $(this).val();
if(val === "Uncheck All") {
$('input:checkbox').removeAttr('checked');
});
I have used this in your fiddle and it works fine.
If you want to find specifically then you can use like this
$('.number-1').find('input[type=checkbox]:checked').removeAttr('checked');
$('.number-2').find('input[type=checkbox]:checked').removeAttr('checked');
$('.number-3').find('input[type=checkbox]:checked').removeAttr('checked');
$('.number-4').find('input[type=checkbox]:checked').removeAttr('checked');
You can also apply any loop here.

JQuery - Output the class name of checked checkboxes

I am wondering whether or not it is possible to output the class name of checked checkboxes each time a checkbox is checked/unchecked? For example, I have 3 checkboxes. If I check one, it'll output its class name, if I then check a 2nd one it'll output the first checkbox class name + the 2nd class name. If I then uncheck the first checkbox, it'll only output the class name of the 2nd checkbox.. and so forth? I made a JSFiddle to get started... http://jsfiddle.net/LUtJF/
Thanks
$("input[type='checkbox']").change(function() {
var classes = $("input[type='checkbox']:checked").map(function() {
return this.className;
}).get().join(",");
alert(classes);
});
Your fiddle, fiddled with.
Check this fiddle: http://jsfiddle.net/eUse5/
Code:
function showChecked() {
var s = '';
$('input:checked').each(function() {
if(s!='') s += ', ';
s += $(this).attr('class');
});
alert(s);
}
$('input[type="checkbox"]').change(showChecked);
$(document).ready(function() {
var cb = $('input[type=checkbox]');
cb.change(function() {
cb.each(function() {
if ($(this).is(':checked')) {
alert($(this).attr('class'));
}
});
});
});
It can be done like
$(":checkbox").click(function(){
var classes = "";
$(':checked[class]').each(function(){ // this will filter only checked checkbox having class attribute
classes += " "+$(this).attr("class");
});
alert(classes);
});
fiddle: http://jsfiddle.net/LUtJF/7/

jQuery multiple radio buttons and load html code?

You think is right this way for show HTML code in each click on radio?
What is you propose to animate (effect) appropriate for show and hide html code?
see you example of my codes: http://jsfiddle.net/9LECb/
$('#housing_select input').click(function(){
var classes = $(this).attr('id');
if(classes == 'hotel_select'){
$('.hotel_apartment_select, .suite_select').hide();
$('.'+classes).show();
}
if(classes == 'hotel_apartment_select'){
$('.hotel_select, .suite_select').hide();
$('.'+classes).show();
}
if(classes == 'suite_select'){
$('.hotel_select, .hotel_apartment_select').hide();
$('.'+classes).show();
}
})
With respect
You can remove the if conditions and minimize the code to:
$('#housing_select input').click(function() {
var classes = $("." + this.id);
$('.hotel_apartment_select, .suite_select, .hotel_select').not(classes).hide();
classes.show();
})
JSFiddle: http://jsfiddle.net/9LECb/2/
Note:
You can check jQuery UI Tabs as they acheive a similar effect
Try this:
$('#housing_select input').click(function() {
$('.hotel_apartment_select, .suite_select, .hotel_select').not("." + this.id).hide();
$("." + this.id).show();
})

How can I check if a checkbox is checked on click?

I need to trigger some code when I click a checkbox based on if a checkbox is checked or not.
But for some reason, .is(':checked') is always triggered.
This is my code.
jQuery('#selectlist input[type=checkbox]').live('click',function(){
var select_id = jQuery(this).attr('id');
if(jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
// Remove some data from variable
} else {
alert('You have checked the checkbox');
//Add data to variable
}
}
UPDATE
I've added an example on JSFiddle: http://jsfiddle.net/HgQUS/
Use change instead of click
$(this).val();
or
$(this).prop('checked'); # on jquery >= 1.6
You will be better at searching over SO:
Get checkbox value in jQuery
How to retrieve checkboxes values in jQuery
Testing if a checkbox is checked with jQuery
this.checked
Should tell you if the checkbox is checked or not although this is just javascript so you won't be able to call it on a 'jquery' element. For example -
<input type="checkbox" id="checky">
$("#checky")[0].checked
If the input has the checked attribute, then it is obviously checked, it is removed if it is not checked.
if ($(this).attr("checked")) {
// return true
}
else {
// return false
}
However, you can adapt the above code to check if the attribute, if it is not removed and instead set to true/false, to the following:
if ($(this).attr("checked") == "true") {
// return true
}
else {
// return false
}
Additionally, I see you use jQuery as an operator for selectors, you can just use the dollar, $, symbol as that is a shortcut.
I flipped-flopped the alerts, and it works for me:
<script type="text/javascript">
jQuery('#selectlist input[type=checkbox]').live('click',function(){
var select_id = jQuery(this).attr('id');
if(jQuery(this).is(':checked')) {
alert('You have checked the checkbox');
// Remove some data from variable
} else {
alert('You have unchecked the checkbox');
//Add data to variable
}
});
</script>
Your "if" syntax is not correct.
jQuery('#selectlist_categories input[type=checkbox]').live('click',function(){
var cat_id = jQuery(this).attr('id');
// if the checkbox is not checked then alert "You have unchecked the checkbox"
if(!jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
} else {
//else alert "You have checked the checkbox"
alert('You have checked the checkbox');
}
});
if you're confused about why it says unchecked when you check it. There is nothing wrong with your code you can just switch the unchecked and checked with each other in the alerts like this:
$('#selectlist_categories input[type=checkbox]').on('change',function(){
var cat_id = $(this).attr('id');
let cat_idText = $("input[type=checkbox]:checked").val();
if(jQuery(this).is(':checked')) {
alert('You have checked the checkbox' + " " + `${cat_idText}`);
} else {
alert('You have unchecked the checkbox');
}
});
PS: I have updated the script to work in jQuery 3.5.1 the original with the live() only works on jQuery 1.7 since it was removed in 1.9 to instead use on() and on jQuery 3.5.1 you can use $ instead of jQuery and the val() function works on all versions because it added in jQuery 1.0
Or in a nice better fashion correct the if statement as RickyCheers said adding the ! before jQuery or $ which then the if statement will turn it into a if jQuery Element is not checked
$('#selectlist_categories input[type=checkbox]').on('click',function(){
var cat_id = $(this).attr('id');
if(!jQuery(this).is(':checked')) {
alert('You have unchecked the checkbox');
} else {
alert('You have checked the checkbox');
}
});

Categories