Tips on using jQuery to check if two cards have matched

I have been working on a card matching game using jQuery, and I've encountered an issue. Even though I have written the code to compare two sets of cards, it always goes to the "card match" condition, even when the cards do not actually match.

If you could please help me identify what might be causing this problem in the pair_Cards function:

// compare two class selected
if ($('.selected').length == 2) {
  // first and last data is same data value = match
  if ($('.selected').first().data('card-id') == $('.selected').last().data('card-id')) {
    alert("Card Match");
  } else {
    alert("Card not match");
  }
}

Below is my complete code:

$(document).ready(function() {
  var app = {
    cards: ["ace_of_clubs.png", "ace_of_clubs.png",
      "2_of_clubs.png", "2_of_clubs.png",
      "3_of_clubs.png", "3_of_clubs.png",
      "4_of_clubs.png", "4_of_clubs.png",
      "5_of_clubs.png", "5_of_clubs.png",
      "6_of_clubs.png", "6_of_clubs.png"
    ],
    init: function() {
      app.shuffle_cards();
    },
    shuffle_cards: function() {
      var random, temp;

      for (i = 1; i < app.cards.length; i++) {
        random = Math.round(Math.random() * i);
        temp = app.cards[i];
        app.cards[i] = app.cards[random];
        app.cards[random] = temp;
      }
      console.log(app.cards);
      app.assign_Cards();
    },
    assign_Cards: function() {
      $('#distribute').click(function() {
        $('.card_ img').css({
          "opacity": "0"
        });
        $('.card_').addClass('removebg');

        $('.card_ img').each(function(index) {
          $(this).attr("src", "img/" + app.cards[index]);
          
          $(this).attr("data-card-id", app.cards[index].length);
        });
        alert("Cards have been assigned randomly.");
        app.click_Handlers();
      })
    },
    click_Handlers: function() {
      $('.card_ img').click(function() {
        $(this).data('card-id');
        $(this).addClass('selected');
        $(this).css({
          "opacity": "1"
        });
        app.pair_Cards();
      });
    },
    pair_Cards: function() {
      if ($('.selected').length == 2) {
        
        if ($('.selected').first().data('card-id') == $('.selected').last().data('card-id')) {
          alert("Card Match");
        } else {
          alert("Card not match");
        }
      }
    }
  };
  app.init();
});
.wrapper {
  margin: 0 auto;
  padding: 0;
  position: relative;
  max-width: 100%;
  width: 1080px;
}

[class^="card_"] {
  background: url(img/back.png) no-repeat center top;
  display: inline-block;
  vertical-align: top;
  position: relative;
  width: 159px;
  height: 238px;
  border: 2px solid #000;
  margin: 0 auto 6px;
}

[class^="card_"] img {
  width: 157px;
  height: 238px;
}

.main_con {
  text-align: center;
  position: relative;
}

.removebg {
  background: none;
}

#distribute {
  display: block;
  margin: 30px auto 10px;
  border: 2px solid #000;
  background: #f00;
  color: #fff;
  text-transform: uppercase;
  padding: 0;
  border-radius: 5px;
  width: 200px;
  height: 45px;
  line-height: 45px;
  text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main_con">
  <div class="wrapper">
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>
    <div class="card_"><img src="" alt="" class="unmatched"></div>

    <a href="#" id="distribute">Distribute Cards</a>
  </div>
</div>

Answer №1

When assigning IDs to cards, ensure that each card has a unique identifier for accurate matching results:

$(this).attr("data-card-id", app.cards[index]);

By updating the code as above, you can guarantee proper matching even with different cards clicked.

UPDATE:

Make sure to adjust your if statement accordingly:

if($('.selected').first().find('img').data('card-id') === $('.selected').last().find('img').data('card-id'))

It's crucial to read and compare data attributes from the same type of elements, such as img to img instead of div to img.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I insert mock data into a datatable using Django?

I recently completed a small application using django. In order to implement datatables, I used the code from django_datatables_view.base_datatable_view import BaseDatatableView import. This datatable displays results directly from the queryset. I now h ...

Guide to showing the current time with ng-forms

Implement a time input using ng-forms <input type="time" class="form-control" path="time" formControlName="time" [ngClass]="{'is-invalid': submitted && f.time.errors}" /> ...

Ajax in action

I've encountered a problem with my JavaScript function. The function is supposed to display an alert when called without AJAX, but it's not working when I include AJAX. Here's the function: function stopSelected(){ var stop=document ...

The resulting line will consist of the discovered string

Let's say there's an interesting HTML document presented below with associated line numbers: 30 - <div id="myDiv"> 31 - <span class="mySpan">Some Text</span> In this scenario, PHP is being utilized for a specific purpose: $ ...

CSS overflow property determines whether to display or hide the parts of an element

Is it possible to create HTML text that will automatically hide itself entirely if it exceeds the container size, instead of clipping with the overflow: hidden property? ...

Achievement with ajax: If the status code is 200, execute one function; otherwise, execute a

I can't figure out why this isn't working... I'm using $.ajax to run file.php and pass a POST value from an input field. Even though the file.php is functioning properly (it successfully adds a user to my newsletter), my ajax function seems ...

Intermittent loading issues with Highcharts using AJAX requests

We've encountered intermittent errors when using Highcharts. Despite our efforts, we can't seem to pinpoint the cause of these issues in Chrome: Uncaught Highcharts error #16: www.highcharts.com/errors/16 VM210:16 HighCharts was already loaded V ...

Sending the result of an AJAX request to the view using C#

I am currently utilizing Ajax to trigger an action in the controller. The code looks something like this: $('#kitchen').change(function () { var selectedKitchen = $('#kitchen').val(); if (selectedKitchen != '') { ...

Enhance the functionality of datatables pagination click by removing and restoring it

I have a datatable set up on a webpage with numerical pagination buttons for First, Previous, Next, and Last, as well as individual number buttons. Each row in the datatable has an 'Edit' link. I want to disable the pagination functionality when ...

Simple JavaScript numeric input field

Hey there, I'm a beginner learning JavaScript. I'm currently working on creating a program that adds numbers input through text fields. If you want to check out the HTML code, visit this link on JS Fiddle: http://jsfiddle.net/fCXMt/ My questio ...

Could an element's loading be postponed on the initial page a user lands on?

One of my clients has requested a live chat system to be added to their website. I am fully capable of implementing it, and it is included through a script tag. Additionally, they have asked for a slight delay before the chat system loads in. My initial t ...

Struggling to retrieve JSON information from the database using AJAX

I am facing a challenge when it comes to fetching data from my database using these technologies. Here is the current scenario: var username = $('#username').val(); var password = $('#password').val(); // This IP is just an example fo ...

Floating above a surface to manipulate a title

Wondering if it's possible to achieve this without JavaScript, but that would be the ideal scenario. Here's a snapshot of how my page is structured: ____________________________ | TITLE | |This is a fixed header. I wa ...

Populate the browser screen with a series of unpredictable numbers

I'm looking to fully populate the visible window of a webpage with random numbers. My current approach involves generating a long string of random digits first, and then applying the following properties to a div: #mydiv{ font-family: "Inconso ...

Maintain the link's functionality even after it's been clicked by utilizing the same

I have a fixed navbar with same-page anchors and I want to keep the link active after it has been clicked and taken to that section of the page. While this is simple for links to another page, I'm struggling to figure out how to do it here. Here&apos ...

How can I search for a particular string in JavaScript?

I have a unique custom div that has been modified to function as an input element. Inside this custom div input element, there is a <p> tag with a default placeholder text. My goal is to verify whether the content of this div is empty or contains new ...

Styles and CSS have been successfully loaded, however, the content is not appearing

After attempting to import a web HTML CSS template into my self-made MVC, I encountered an issue. While the template works properly on its own, it fails to connect to the CSS files and display proper styles when accessed through my controller. Instead, onl ...

jQuery UI Datepicker extending beyond its bounds

My Datepicker is expanding and filling the entire screen. What could be causing this issue? Here is my code: Additionally, how can I change the date format in jQuery to appear as dd-mm-yyyy? https://i.stack.imgur.com/IQzVV.png HTML: <!DOCTYPE html&g ...

What is the best way to find the right construction match?

Currently, I am in the process of parsing text and looking to match a specific type of text that I want to remove entirely. The format of the text I am trying to target is as follows: <tr class="label-BGC"><td colspan="4">any content here</ ...

Is it possible to tap into the stylus Abstract Syntax Tree (AST) for

Is there a way to access the abstract syntax tree (AST) of the CSS style generated by stylus without re-parsing it using css-parse? I'm curious if the AST of the generated styles can be accessed publicly. ...