0

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

1
  • 1
    here: var x = $('cont you missed a dot. Commented Dec 31, 2016 at 14:30

3 Answers 3

3

Two problems:

  1. You forgot to close the attribute selector

  2. 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>

Sign up to request clarification or add additional context in comments.

Comments

1

I see that your selector is wrong. The class dot is missing. Try with this:

$('.cont[key="' + $(this).attr('key') + '"')

1 Comment

That's half the problem, yes. :-)
1

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);
});

1 Comment

That's half the problem, yes. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.