user3330609 user3330609 - 8 days ago 6
Javascript Question

A function search every class with name .resultsblock and if is visible put a data in array

Hiho,
A function search every class with name .resultsblock and if is visible put a data in array.

The problem is when the first class is "display: block" all futures values return true and will be ut in array, included the "display:none" and if the first one is "display: none" all values return false...

<div id="measure_print" class="resultblock" data-nid="900" style="display: block;">
<p>blablalblabla</p>
</div>
<div id="measure_print" class="resultblock" data-nid="988" style="display: none;">
<p>blablalblabla</p>
</div>
<div id="measure_print" class="resultblock" data-nid="999" style="display: none;">
<p>blablalblabla</p>
</div>



<button type="button" onClick = "cartAction('addall','')" >Add All</button>



function cartAction(action,nID) {
var nidarr = [];
if(action != "") {
switch(action) {
case "addall":
$.each($('.resultblock'), function(index, value) {
var temp = parseInt($(value).data('nid'));
var query = $('#measure_print');


if ($('.resultblock').css('display') !== 'none') {
nidarr.push(temp);
console.log(temp);
}
});
console.log(nidarr);
break;
}
}
}


I made my own solution -->

DEMO LIVE https://jsfiddle.net/kardebadas/j3f9scet/3/

Answer

You are grabbing all of the .resultblock divs instead of only the current iteration. I also recommend jquerys is('visible') for a little cleaner code :)

function cartAction(action,measure_N_ID) {
  var nidarr = [];
  if(action != "") {
    switch(action) {
      case "addall":
        $.each($('.resultblock'), function(index, value) {
          var temp = parseInt($(value).data('nid'));
          var query = $('#measure_print');


          if ($(this).is(':visible')) {
            nidarr.push(temp);
            console.log(temp);
          }
        });
        console.log(nidarr);
        break;
    }
  }
}
Comments