TheRealPapa TheRealPapa - 1 year ago 48
JSON Question

JSON element pushing into array in Javascript

I am looking to access a HTML element's data (a JSON record) and push it into an array in JavaScript.

The HTML is:

<td class="card-holder" data-card="{"id":0,"type":"Wildcard","image":"wildcard.png","strength":0,"type_image":"wildcard.png","region_owned_adder":0}">
<img id="card-image-0" src="/img/wildcard.png" class="card-exchange">
<input class="cards-checkbox" type="checkbox" id="card-0" name="cards_to_exchange[]" value="id=" 0""="">
<label for="cards_to_exchange"></label>

I have a number of these on my page. I read each in a loop and select some to push into an array like this:

var cards = [];
$('.card-exchange').each(function() {
if ($(this).find('input[name="cards_to_exchange[]"]').is(':checked')) {
var parseCard = JSON.parse('card'));

But this is showing me
after the loop:


This shows the data OK:


How do I read the string and push it into array as object? Thanks.

Answer Source

You're using .find() on an <img>, which has no descendants.

Use .next() instead to get its <input> sibling.

Also, you can use .filter() and then .map() to clean it up a little.

var cards = $('.card-exchange').filter(function() {
    return $(this).next().is(':checked');
}).map(function() {
    return JSON.parse('card'));

Though I'm not sure what thisElement is referring to.

You could even shorten it a little more.

var cards = $('.card-exchange + input:checked')
  .map(function() {
     return JSON.parse('card'));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download