Reputation: 2091
<div class="parent">
<div class="click"></div>
<div class="subdiv">
<input value="1">
<input value="2">
</div>
</div>
I have the following code, and onclick
event on click div
. Now I want to iterate over all input
s in this specific parent div
(there are many).
So I wrote something like this:
$(this).parent().children('.subdiv input').not(':checked').length
It should output something like 1, or 2, depending of how many input
s are unchecked. But it always shows 0.
Why is that so?
Also, how can I check/uncheck them all?
$(this).parent().find('.subdiv input').not(':checked').each(function() {
// $(this) is undefined, or shows 0
});
Upvotes: 0
Views: 81
Reputation: 11750
First of all you should declare those inputs as checkboxes:
<input type="checkbox" value="1" />
Then, on click of .parent
element:
$('.parent').on('click', function() {
// alert the number of checked checkboxes
alert($(this).find('input[type="checkbox"]:checked').length);
});
In order to check a checkbox, use prop()
function:
$('input[type="checkbox"]').prop('checked', true); // sets input to checked state
In order to get the value of a checkbox:
var value = $('input[type="checkbox"]').val();
DEMO
$('.parent').on('click', function() {
var n = $(this).find('input[type=checkbox]:checked').length;
alert('There are ' + n + ' checked checkboxes');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="parent">
<div class="click"></div>
<div class="subdiv">
<input type="checkbox" value="1">
<input type="checkbox" value="2" checked>
</div>
</div>
Upvotes: 2
Reputation: 82251
Input text do not have checked/unchecked property. You need to define type as checkbox for input elements:
<input type="checkbox" value="1">
<input type="checkbox" value="2">
also you can narrown down the selector to get unchecked checkboxes to:
$(this).parent().find('input:not(:checked)').each(function() {
// $(this) is undefined, or shows 0
});
Upvotes: 0
Reputation: 31749
By default input
s will be text
. And checked
property does not work with text fields. It should be checkbox or radio. Try with -
<div class="subdiv">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
</div>
Upvotes: 1
Reputation: 2581
ASsuming all the inputs are checkbox or anything that can be checked Use the below 1>No of inputs checked
$(this).parent().find('input:checked').length
1>No of inputs unchecked
$(this).parent().find('input').not(':checked').length
Upvotes: 1