mdixon18
mdixon18

Reputation: 1219

JQuery Loop through classes and then compare an attribute and determine if any matches were found

Basically I am trying to check if something has been created and if it has the value of an attribute assigned.

So for this, I am basically looking for all the $('.item') classes and for this example these items have an attribute like data-value="1" and each item in the html has a unique value for this attribute such as:

<div class="item" data-value="1">Item 1</div>
<div class="item" data-value="2">Item 2</div>
<div class="item" data-value="3">Item 3</div>

To trigger our JQuery we will have a button that is designed to correspond to an item:

<button class="button" data-value="1">Button for Item 1</button>
<button class="button" data-value="2">Button for Item 2</button>
<button class="button" data-value="3">Button for Item 3</button>
<button class="button" data-value="4">Button for Item 4</button>

So now in jQuery I will like to look through them and run a function to create a new one if it doesn't exist.

This is how I interpret this but it doesn't work: (lets presume this is within a function triggered by the click.

var itemClicked = $(this);
var findItem = $('.item').each(function() {
  if ($(this).attr('data-value') == itemClicked.attr('data-value')) {
    return true;
  }
});
if (!findItem) {
  // create new item
}

So in theory, button 1, button 2 and button 3 would pass the test and a new item wouldn't be created. However button 4 would fail the check and create a new item essentially.

But i can't get the check to work how can I go about it?

Upvotes: 0

Views: 63

Answers (3)

luinix
luinix

Reputation: 21

Just copy this :

var itemClicked = $(this);
var findItem = ($('.item[data-value="' + itemClicked.attr('data-value') + '"]').length > 0 );
if (!findItem) {
  // create new item
}

Upvotes: 0

Mathieu Labrie Parent
Mathieu Labrie Parent

Reputation: 2606

You can do something like this :

$("input[type=button]").click(function () {
    if($("div[data-value='"+ $(this).data("value") +"']").length == 0 ){
        // create new item
    }
});

UPDATE

http://jsfiddle.net/o6q8ew4z/

Upvotes: 3

diegoyucra
diegoyucra

Reputation: 24

Do this:

var itemClicked = $(this);

var createIem = function(){
    //enter code here
};

var findItem = $('.item').each(function() {
  if ($(this).attr('data-value') == itemClicked.attr('data-value')) {
    createIem();
  }
});

Upvotes: -1

Related Questions