Adam
Adam

Reputation: 20882

jquery + read multiple img src

I have around 8 img src tags that start like this:

<img src="" id="joinCityResponse" class="joinResponse"/>

If a related question is answered correctly then jQuery adds in the src field. src="http://www.staticimages.co/dating/online-dating-index/join_tick.png"

At the end of the 8 questions I have a Join Now button and I need to be able to know if all the questions have been answered correctly. eg: have the above src url set.

How can I use jQuery to check all img tags with the class 'joinResponse' have the scr as set above?

Upvotes: 0

Views: 1521

Answers (3)

kubetz
kubetz

Reputation: 8556

Try:

var allAnswered = $('img.joinResponse').filter('[src="url"]').length == 8;

This will get all images with joinResponse class and then return only those that have the src attribute set to url value (replace url with your png url).

I would recommend you insteadto just set another class that will mark correctly answered answers. Then you can just check the number of elements with this class. The advantages are:

  1. Checking if all answers are correct is faster (the selector is faster).
  2. You won't have the URL hardcoded in multiple places so the code is easier to modify. If you have single variable containing this URL and you are using it everywhere, then ignore this :).

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

You can use

var responses = $('.joinResponse');
if (responses.length === responses.filter('[src$="join_tick.png"]').length)){
  // all are correct
}

This will check if all the .joinResponse elements have an src that ends with join_tick.png

Upvotes: 1

Etienne Perot
Etienne Perot

Reputation: 4882

Something like this?

var allSet = true;
$('img.joinResponse').each(function() {
    if(!$(this).attr('src')) {
        allSet = false;
    }
});
// allSet now contains whether all images with the class "joinResponse" have an src attribute that is set to a non-empty string

Not the most efficient since it doesn't stop as soon as it finds one such no-src image tag, but if there's only 8 image tags, this should be enough.

Upvotes: 0

Related Questions