If DIV contains checked checkbox set display to block - javascript

I have a menu consisting of sort criteria. The options per criteria are listed as check boxes in a div wioth class '.collapse_box'.
I need to check each of these div's to see if any of the checkboxes it contains are checked. If there are any checkedboxes I need to set the DIV display to block.
I was thinking along these lines:
$('.collapse_box')each(function()
if( $(this).(input:checked).length() > 0{ //here lies my problem
$(this).show();
}
});
Seeing that I am very new to javascript and jquery I don't know how to return the checked boxes for $(this). Or better said: the correct method to check if any checkboxes in $(this) are checked.

Your selector is wrong, element are always given as string or object:
if( $(this).find('input:checked').length > 0){
Also, length isnt a function, but a property. And you forgot the .find()
Made you a jsFiddle with demo

Alright, assuming that the inputs are children, something like this will work:
$('.collapse_box').each(function(){
if($(this).find('input').prop('checked')){
$(this).show();
}
});
The .prop('checked') piece returns a boolean value of whether the input is checked or not.
EDIT Martijn makes a good point, you can switch it to vanilla JS with a mod to the selector.
$('.collapse_box').find('input').each(function(){
var self = this;
if(self.checked){
self.style.display = 'block';
}
});

Related

Updating a value on click once when multiple element exists

I have a fiddle here http://jsfiddle.net/wMUTg/56/ that I'm trying to update a value by one when a button is clicked, only once. Similar to the 'like' functionality on facebook. I've got that working, however if I have multiple elements that are similar only one is updating. I know I have to use the $this functionality but I'm struggling to find where to put it. Also, does anyone know if this can be achieved without an input field? Ideally I'd like it to be in a span tag but I needed the input to get the value first.
$(".red #update").one("click", function() {
var val;
val = $('#counter').val();
val++;
$('#counter').prop('value',val );
});
#CertainPerformance, is right. You should use class instead of same multiple IDs in one DOM.
However here is your solution:
Used $(this).prev('#counter') as selector to refer relevant element.
$(".red #update").one("click", function() {
var val;
val = $(this).prev('#counter').val();
val++;
$(this).prev('#counter').prop('value',val );
});

Jquery, getting 'this' selector from a conditional

I have several elements on my page with the 'checkbox' class. When clicked, a corresponding checkbox input is checked. However, I need to have JQuery check if the checkbox element is active when the page first loads, and check the checkbox input accordingly at that time.
Since there are multiple 'checkbox' classes on my page, I used the 'this' selector previously and it worked fine, however I do not know how to make it do this with my conditional on page load without the .click action that I used before. Here's what I'm trying to make work:
if($('.checkbox').hasClass('active')) {
$('[name="'+$(this).attr('rel')+'"]').prop('checked', true);
}
Obviously the 'this' selector doesn't know what I'm referring to. Is there a better way of doing this? Since it's checking through a bunch of elements and not just one I'm stumped. Thanks!
You can only use this within the context of a jQuery function, so in this scope it's not going to refer to any .checkbox.
You can use .each instead:
$('.checkbox.active').each(function() {
// In this context, this refers to the DOM element represented by .checkbox.active
$('[name="'+this.rel+'"]').prop('checked', true);
});
The each function may suit your needs:
$('.checkbox').each(function() {
var $this = $(this);
if ($this.hasClass('active')) {
$('[name="'+$this.attr('rel')+'"]').prop('checked', true);
}
});
If the checkboxes must be unchecked when the active class is absent, then:
$('.checkbox').each(function() {
var $this = $(this);
$('[name="'+$this.attr('rel')+'"]').prop('checked', $this.hasClass('active'));
});

jQuery remove tr with no results

I have a SQL-PHP printed table, and a select at the top of the table. The table contains contacts classified by towns.
At the beginning, the table shows all contacts. If I specify the town, I want to hide the rest.
I'm trying to use a jQuery script
<script>
function updateit(){
if ($("#table").filter("tr") === $("#selectTown").val()) $(this).show(););
else {$(this).hide();};
}
</script>
[...]
<select id="selectTown" onchange="updateit()"><option value="NY">New York</option><option value="TX">Texas</option></select>
<table id="table">
bla bla bla...
</table>
Before I tried with find() function, but with no success.
Any suggestions?
This line $("#table").filter("tr") === $("#selectTown").val() compares document elements to string, it would not work.
Simplest solution would be to do all elements hidden and than select and show all matching elements. Example:
$('tr').hide();
$('tr[value=' + $("#selectTown").val() + ']').show();
I'm not sure where you got the idea for this code, but filter() definitely doesn't do what you think it's doing. $("#table").filter("tr") is going to give you a list of tr elements in the table. That list itself isn't going to equal any selected value, it's just an array of elements.
Mocking up a few things in a jsFiddle here, perhaps you want something more like this:
$('#selectTown').change(function () {
$('#table tr').hide();
$('#table tr').filter(function () {
return $(this).find('td:first').text() === $('#selectTown').val();
}).show();
});
What this does is:
Bind to the change event of the select element (which is preferred over the inline binding you do in your markup, just in general).
Hide all of the tr elements first, you'll show the ones you want in a moment.
Show all of the tr elements which match the filter.
The filter in this case is a function which returns true if the text inside of the td element (you will likely need to update that selector) equals the selected value. The main difference here vs. what you tried is that .filter() is returning a list of matched (filtered) elements, not an actual value to compare. Internal to the filter is where the comparison takes place, in this case using a function (which needs to return true or false for any given element being filtered).

Display number of checked checkboxes in jQuery

I am quite new to jQuery, I think this might be quite easy for many of you, but I can't seem to make it work. How can I display the number of checkboxes so that the value increases or decreases.
i tried the following but with the number in the span tag remains 0: http://jsfiddle.net/yunowork/NTwxc/
Thanks
You should listen to the change event:
$('input[type=checkbox]').on('change', function(){
var number = $('input[type=checkbox]:checked').length;
$('.totalchecked').text(number);
});
http://jsfiddle.net/NTwxc/7/
Note that val is used for getting/setting values of form elements, for other elements like span element, text or html methods should be used.
Number of checked checkboxes:
$(":checkbox:checked").length
http://api.jquery.com/checked-selector/
edit: I see in your fiddle that you already had that. I'll leave it there, since that's actually the answer to "how to display the number of checked checkboxes"...
The problem is that you're not updating and looking to see how many are checked. You need to re-run that function whenever any of the items are checked.
$(":checkbox").change(function () {
// update the span with $(":checkbox:checked").length ...
});
You shouldn't be setting .val of a span, but .text.
Also, you need to update it every time the checked state changes.
function calc() {
$('.totalchecked').text($(':checkbox:checked').length);
}
$(calc);
$(':checkbox').change(calc);
Demo
Here we are!
$('input[type="checkbox"]').change(function() {
$('.totalchecked').empty().text($('input[type="checkbox"]:checked').size());
});
http://jsfiddle.net/toroncino/PTvG8/
Problems: .val() is for form elements only. To set the content of an element, use .text() or .html() if you are inserting HTML. Second problem is that you need to register a listener to "change" events. Otherwise, the value won't update.
Updated solution: http://jsfiddle.net/NTwxc/4/
$("input[type=checkbox]").change(function(){
var number = $('input[type=checkbox]:checked').length;
$(".totalchecked").text(number);
});
​
By the way, I would personally prefer input[type=checkbox]rather than :checkbox. The former works for both CSS and jQuery.

I want to check if `id` has no content

I want check between id that get in var span, if empty was between it put css for input but it not work. how can fix it?
var span = '#'+$('.valid').closest('.auto_box').find('span').attr('id');
if ($(span+':empty').length != 0) {
//alert('ok')
(this).closest('.auto_box').find('input').css('background-color','#000');
}
See here my full code: http://jsfiddle.net/Pjqv2/2/
You are using (this) instead of $('.valid') or whatever you meant with it. Also, you are doing this the wrong way; .find('span') returns the jQuery objects set for that span.
You don't need to get it's ID and then check on that ID again. More importantly, your code seems the need to run on multiple instances of .auto_box. For that, you need to iterate on the set found by (".valid").closest(".auto_box"), which you can do with the jQuery .each() (.each() in jQuery docs) like this:
var autoBoxes = $(".valid").closest(".auto_box");
autoBoxes.each(function(){
if ($(this).find("span").is(":empty")) {
$(this).find("input").css("background-color", "#000");
}
});
Your updated jsfiddle with this script: http://jsfiddle.net/dvir_azulay/Pjqv2/4/
Change (this) to $(span). I updated your fiddle to reflect this change.

Categories