MrJesus
MrJesus

Reputation: 11

Attempting to append an image count for specific image types | jQuery

I want this function to print the number of ball pictures or the number of firetruck pictures upon user click:

function imageCounter (){

var ballCount = 0;
var truckCount = 0;

$('img[src*=ball]').each(function(){
    if($(this).prop("checked")){
        ballCount+=1;
    }     
    $('#radioButtons').append("There are " + ballCount + " ball images.");
 });


$('img[src*=truck]').each(function(){
    if($(this).prop("checked")){
        truckCount+=1;
    }
    $('#radioButtons').append("There are " + truckCount + " truck images.");
    });

}

I feel like I'm close..

I have 4 ball images, and 1 firetruck image. My code currently doesn't give me the number value of images, instead it prints out the output message 4 times for the balls, and 1 time for the firetruck.

Any advice on where to go from here?

Upvotes: 0

Views: 68

Answers (2)

Pat
Pat

Reputation: 2750

I notice a couple things. First thing being that $(this).prop("checked") will be called on the <img> tag, which are not checked unless you are setting them to checked somewhere else in code that's not shown here. (meaning truckCount and ballCount are not incremented)

Second being the fact that $('#radioButtons').append(...) is being called within your each "loop" so to speak so it will be appending that line for every <img> tag that matches the selector.

Upvotes: 1

Benny Lin
Benny Lin

Reputation: 536

you just need to move the append message line out of the foreach loops:

function imageCounter() {

  var ballCount = 0;
  var truckCount = 0;

  $('img[src*=ball]').each(function () {
    if ($(this).prop("checked")) {
      ballCount += 1;
    }
  });

  $('#radioButtons').append("There are " + ballCount + " ball images.");

  $('img[src*=truck]').each(function () {
    if ($(this).prop("checked")) {
      truckCount += 1;
    }
  });
  $('#radioButtons').append("There are " + truckCount + " truck images.");
}

Upvotes: 1

Related Questions