Reputation: 1164
So, I'm writing some JS which dynamically creates some DOM elements. Below is a structure of the elements created:
<div class='list_item' key='1'>
<p>Hello, World!</p>
</div>
<div class='cont' key='1'>
<input type='checkbox' name='test'/>
</div>
When an event is triggered, I want to loop through all .list_item
, and find their corresponding .cont
, using the key
attribute as an identifier. I want to find the value of the .cont > input[type="checkbox"]
.
Here's my code so far:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
console.log(x);
});
Instead of getting a true
or false
response, my code throws undefined
as its result. What can I do to my code to get the response I want (the value of the checkbox)?
Thanks
Upvotes: 0
Views: 52
Reputation: 729
you just missed '.' before class selector
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
console.log(x);
});
Upvotes: 1
Reputation: 1074148
Two problems:
You forgot to close the attribute selector
You forgot the .
before cont
in the class selector
So:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"]').find('input[type="checkbox"]').prop('checked');
// ------------^--------------------------------------^
console.log(x);
});
Note that you can do that with a single selector rather than find
:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"] input[type="checkbox"]').prop('checked');
console.log(x);
});
Example:
$('.list_item').each(function() {
var x = $('.cont[key="' + $(this).attr('key') + '"] input[type="checkbox"]').prop('checked');
console.log(x);
});
<div class='list_item' key='1'>
<p>Hello, World!</p>
</div>
<div class='cont' key='1'>
<input type='checkbox' name='test' />
</div>
<div class='list_item' key='2'>
<p>Hello, World!</p>
</div>
<div class='cont' key='2'>
<input type='checkbox' name='test' />
</div>
<div class='list_item' key='3'>
<p>Hello, World!</p>
</div>
<div class='cont' key='3'>
<input type='checkbox' name='test' checked/>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 3
Reputation: 15713
I see that your selector is wrong. The class dot is missing. Try with this:
$('.cont[key="' + $(this).attr('key') + '"')
Upvotes: 1