What is the process for choosing corresponding values in jQuery?

Hello, I am a beginner in programming and I am currently working on developing a word guessing game. Here is the code I have written so far:

  • The (letter) represents the key being typed by the player
  • Var compareLetters = $('.letter') represents the empty boxes at the top
  • Const game = new Game() creates a new instance of a class constructor named Game, which includes a property called this.phrases containing an array of phrases

showMatchedLetter(letter) {
  // If there was a match on the checkLetter method, add a show-letter class
  
  // Grab letters and store them in a variable
  var compareLetters = $('.letter');
  
  // Create a new game instance to access the array property for the loop below
  const game = new Game()
  
  // Assign the phrase array to a variable for reference
  const phraseArray = game.phrases;
  console.log(phraseArray)
  
  /* Use the each method to iterate through the array of Phrase characters,
    and compare each character to the letter selected by the player.
    */
  compareLetters.each((i, compareLetters) => {
    if ($(compareLetters).text() === letter) {
      $('.letter').addClass('show letter');
    }
  });
}

I am working to reveal the correct letters guessed by the player. Although my code functions, I am encountering an issue where instead of just showing the matching letters, the entire phrase is revealed. Can someone please assist me with this?

Answer №1

In order to add the show class only to the specific matching panel, utilize the each function where the keyword this refers to the current element in the matched set:

function showMatchedLetter(letter) {    
    $('.letter').each(function() {
        if ($(this).text() === letter) {
            $(this).addClass('show');
        }
    });
}

Example:

$(function() {

  function showMatchedLetter(letter) {
    $('.letter').each(function() {
      if ($(this).text() === letter) {
        $(this).addClass('show');
      }
    });
  }

  $("input").change(function(e) {
    let letter = $(e.target).val()
      .replace(/[^a-z]/ig, '')
      .toUpperCase().substring(0, 1);

    showMatchedLetter(letter);

    $(e.target).val('');
    setTimeout(_ => $(e.target).focus(), 100);
  });
});
span.show {
  background-color: gray;
}

div {
  width: 280px;
}

div>span {
  color: black;
  background-color: black;
  display: inline-block;
  opacity: 1;
  width: 25px;
  height: 25px;
  line-height: 25px;
  text-align: center;
  border: 2px solid blue;
  padding: 0px;
  margin: 3px 0px 0px 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input placeholder="Enter a letter" /><button>Go</button>
<div>
  <span class="letter">A</span>
  <span class="letter">B</span>
  <span class="letter">C</span>
  <span class="letter">D</span>
  <span class="letter">E</span>
  <span class="letter">F</span>
  <span class="letter">G</span>
  <span class="letter">H</span>
  <span class="letter">I</span>
  <span class="letter">J</span>
  <span class="letter">K</span>
  <span class="letter">L</span>
  <span class="letter">M</span>
  <span class="letter">N</span>
  <span class="letter">O</span>
  <span class="letter">P</span>
  <span class="letter">Q</span>
  <span class="letter">R</span>
  <span class="letter">S</span>
  <span class="letter">T</span>
  <span class="letter">U</span>
  <span class="letter">V</span>
  <span class="letter">W</span>
  <span class="letter">X</span>
</div>

Answer №2

Perhaps consider altering the:

$(this).addClass('show letter'); //Or you can replace this with a relative parent and child selector like $(this).parent(), $(this).children()

Instead of using:

$('.letter').addClass('show letter');

This way, it will specifically target the current HTML element you are focusing on.

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

Is there a way to replace the message 'no rows to show' with a custom component in ag-Grid for react?

Currently, I am utilizing ag-grid in my React application https://www.ag-grid.com. When the table or grid is empty, it displays the default message "No rows to show." However, I am interested in customizing this message or possibly incorporating a custom ...

Exploring the drag-and-drop feature in Ruby on Rails version 3

Is there a way to replicate drag and drop actions in rspec request specs? In my scenario, I need to move the #divItem element to the #divContainer element using jQuery. After refreshing the page, I want to verify that the #divItem is now inside the #divCo ...

Video HTML autoplay feature malfunctioning

I have been attempting to use the <embed> tag in order to showcase a video on my webpage. However, I have encountered an issue where the video begins playing automatically when the page loads. In an effort to remedy this situation, I included autost ...

Having trouble loading IE with jQuery isotope

Encountering a common issue on an unfamiliar browser, many still face the challenge. Setting up an isotope grid on websites seems to function seamlessly across various browsers, except for when testing in Internet Explorer using . In this case, the layout ...

The icon must be aligned to the right and able to adapt to different

I'm attempting to align a Font Awesome icon to the right while keeping an input field aligned to the left on the same line. Both elements should be responsive and maintain their positions. I've created a sandbox and an image showcasing how it cu ...

Pattern to locate a CSS class identifier

I've been working on creating a regex to match valid CSS class name structures. Currently, my progress looks like this: $pattern = "([A-Za-z]*\.[A-Za-z]+\s*{)"; $regex = preg_match_all($pattern, $html, $matches); However, there are certai ...

Round corners, images in the background, gradients in the background, and compatibility with Internet Explorer versions 8 and

I've encountered an issue where my div with border radius, background gradient, and background image are working fine in FireFox but not displaying correctly in IE8 or IE10. In IE8, the gradient and background image work properly, but as soon as I app ...

What are the benefits of using Bower.js when npm is already functioning well?

When working in the main project directory, running the command npm init will create a file called "package.json". If I need to install dependencies such as angular, jQuery and bootstrap, I can use the following commands: npm install angular --save-de ...

What is the best way to choose content that has been clicked on?

How do I display only clicked content? Currently, I have a system where clicking a button shows the data in the nav tag. The code is written in views.py. class TopView(TemplateView): model = Data template_name = 'index.html' def get ...

What could be causing the right padding to be overlooked next to the scroll bar, and what steps can be taken to address this

https://i.sstatic.net/0laRo.jpg .outer { padding: 50px; } .inner { width: 500px; height: 1000px; border: 1px solid gray; margin: auto; } <div class="outer"> <div class="inner"> <div class="content">qwerty</div> ...

The function fromEvent is throwing an error stating that the property does not exist on the type 'Event'

I'm attempting to adjust the position of an element based on the cursor's location. Here is the code I am currently using: this.ngZone.runOutsideAngular(() => { fromEvent(window, 'mousemove').pipe( filter(() => this.hove ...

Choose a drop-down menu with a div element to be clicked on using Puppeteer

Issue Description: Currently encountering a problem with a dropdown created using material select. The dropdown is populated through an API, and when selected, ul > li's are also populated in the DOM. Approaches Tried: An attempt was made to res ...

What exactly happened to my buttons when I transition to the mobile display?

Due to time constraints, I decided to save some time by utilizing a CSS template called Horizons created by Templated. This particular CSS template uses Javascript to adjust the layout for mobile devices, causing buttons to switch from inline to block for ...

Properly Adding an External jQuery File in HTML Using jQuery

Seeking assistance as a newcomer to JS and programming in general. Currently working on a website where each page has its own HTML / PHP file, with jQuery and global JS functions included in the footer via a separate includes file "footer.php". Everything ...

Various Utilizations through a Single Alexa Skill

In my skill SkillIntent, when asked about a specific game, it provides the description of that skill. Now, I want it to also inform WHO has that Skill when asked differently. Below is the code snippet: 'use strict'; var AlexaSkill = require(&a ...

The issue lies in the error code TS2315 which states that the type 'observable' is not a generic

I keep encountering an error message that says 'observable is not generic' while importing files. I am working on implementing CRUD operations in Angular 7, where I have created two components for adding and listing employees. The functions for c ...

What are some techniques for preventing Null Pointer Exception errors?

Currently, I am working on a project that involves creating a form with a dropdown field for categories. Based on the chosen category, I need to populate a second dropdown called subcaste using AJAX. To achieve this, I have implemented a method that disab ...

Is there a glitch preventing the connection between HTML and CSS in Notepad++ even though the link is correct?

I have encountered a puzzling situation that has left me scratching my head in confusion. Despite being a rookie, I've had experience with linking CSS files before and can't understand why it's not working this time around. This issue is per ...

What is the solution to making text appear on the top rather than on the side?

Seeking a way to keep the text description above the textbox within a definition list, however currently the text appears to the left of the box. Here is the provided HTML structure: <dl> <dt> <label>Phone Number</label> &l ...

Discover the best way to enable lint support for MUI `sx` prop values

Despite attempting the method below, I am still unable to receive lint support to identify incorrect style properties and values. import { SxProps, Theme } from "@mui/material"; export const navBarStyles: Record<string, SxProps<Theme> | ...