When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version:

<div id="main">
    <div id="content_block_1" class="content_block">
        <img id="content_block_button_1" class="content_block_button" src="images/1.png">
        <div id="content_block_textfield_1" class="content_block_textfield>
            This is some text.
        </div>
    </div>
    <div id="content_block_2" class="content_block">
        <img id="content_block_button_2" class="content_block_button" src="images/2.png">
        <div id="content_block_textfield_2" class="content_block_textfield>
            This is more content.
        </div>
    </div>
    <div id="content_block_3" class="content_block">
        <img id="content_block_button_3" class="content_block_button" src="images/3.png">
        <div id="content_block_textfield_3" class="content_block_textfield>
            This is even more content.
        </div>
    </div>
</div>

When users click on the images, they should be able to change the background color of the relevant textfield to yellow. If the textfield is already yellow, it should revert back to its normal background color. If one textfield is highlighted while another already is, the existing highlights should be removed before activating the new one.

I am aware of using the toggle() function to manage the .highlight css class. Here's a simplistic yet inefficient function I developed for this purpose:

//1st
$('#content_block_button_1').click(function () {
    //toggle the associated 
    $('#content_block_textfield_1').toggleClass('highlight');
    //reset other highlights
    $('#content_block_textfield_2, #content_block_textfield_3').removeClass('highlight');
    console.log("toggled highlight 1");
});

//2nd
$('#content_block_button_2').click(function () {
    //toggle the related
    $('#content_block_textfield_2').toggleClass('highlight');
    //reset other highlights
    $('#content_block_textfield_1, #content_block_textfield_3').removeClass('highlight');
    console.log("toggled highlight 2");
});

//3rd
$('#content_block_button_3').click(function () {
    //toggle the respective 
    $('#content_block_textfield_3').toggleClass('highlight');
    //reset other highlights
    $('#content_block_textfield_1, #content_block_textfield_2').removeClass('highlight');
    console.log("toggled highlight 3");
});

This code lacks elegance and scalability. It's clear that a better approach is needed.

I aim to utilize the fact that the button and textfield elements share the same "parent". I seek a way to remove the .highlight class from all textfields except the one directly linked to the button calling the function, without relying on specific ids. Ideally, this solution would work seamlessly regardless of the number of content blocks.

If anyone can provide guidance in the right direction, it would be greatly appreciated.

Answer №1

To make it shorter, you can utilize the wildcard attribute selector that starts with a specific value.

$('[id^=content_block_button_').click(function () {
     $('[id^=content_block_textfield]').removeClass('highlight');
     id = "content_block_textfield_" + this.id.replace('content_block_button_', '');    
     $('#' + id).toggleClass('highlight');
     console.log(id);
});

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

Unable to make changes to the AWS Dynamo array

I am currently attempting to update a JSON array. I have a table in DynamoDB where I successfully inserted the JSON data using the PUT method. Partition key : _id , Type : S Below is the JSON data that has been saved into the database: { "_id": ...

"After refreshing the page, the .load() function did not run as

After loading the page and adjusting the viewport size, I am trying to retrieve the dimensions of images. While I can successfully get image dimensions after the page loads using .load, I am struggling to find a way to update the image sizes when the viewp ...

My router-outlet is malfunctioning when trying to display my component

I am currently diving into learning Angular 2 in order to revamp my personal website. However, I've encountered an issue where my application fails to load the component when I navigate to the appropriate route by clicking on the navigation bar. Insi ...

Excessive form inputs extend beyond the modal when utilizing Bootstrap 3

Having an issue loading a modal with Angular and populating it with a template. The main problem I'm facing is that the inputs are extending beyond the boundaries of the modal - attached below is a screenshot illustrating the problem: Below is the c ...

Updating Input Field with AngularJS Date Format During Input Field Change

Here is the input field for date: <div class="input-group date"> <input type="text" class="form-control" id="datepicker" placeholder="dd/mm/yyyy" ng-model="abs.date"> </div> The value in this field is updated ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable? Javascript var OpenWeatherKey = ' ...

Error encountered: The Bootstrap Carousel function is causing a TypeError as e[g] is not defined

I am attempting to build a dynamic bootstrap carousel using my json data, and I have implemented jQuery-Template for rendering. Essentially, I am generating the carousel slider on-the-fly from my json data with the help of jQuery-Template. Here is a snippe ...

Verify all inputs are complete in the FullScreenForm

I have been working on implementing a form from this website: http://tympanus.net/Development/FullscreenForm/ My main objective is to validate each input when the form is submitted and display any errors that may arise. To achieve this, I have already se ...

Using latitude and longitude coordinates to calculate the xyz position on earth in a three-dimensional environment (three

Exploring the wonders of three.js I am currently working on rendering objects at specific geocoordinates on a large sphere. I am close to finding a solution, but I am struggling to determine the correct xyz position from latitude and longitude. I have cr ...

I'm curious about how to initiate a fresh Rails 7 project while incorporating Bootstrap 5 and jQuery assistance

Looking to start a new Rails project with version 7.3.1 and integrate the latest Bootstrap framework. However, I've heard that jQuery may not be compatible with the latest version of Bootstrap. I am also considering downloading the latest Bootstrap fi ...

Extracting simple data from a JSON response

I am having an issue with extracting an integer value from a JSON response. Below is the code snippet causing the problem: public ActionResult GetCartCount() { int cartItemCount = shoppingCartManager.GetCartItemsCount(); return Json(new { name = c ...

Error: The method 'send' is not available for the object #<ServerResponse>

So I've been diving into building this Express app and all of a sudden, I run into this strange error message that reads TypeError: Object #<ServerResponse> has no method 'send'. It popped up when I was setting up some routing using th ...

Launching a program through a web browser - a step-by-step guide

I am looking to create a specific sequence of events: A web browser opens, and a user logs in (the exact action is not crucial) The user is then redirected to a new page where another program should automatically open This process is similar to what happ ...

Angular 2: trigger a function upon the element becoming visible on the screen

How can I efficiently trigger a function in Angular 2 when an element becomes visible on the screen while maintaining good performance? Here's the scenario: I have a loop, and I want to execute a controller function when a specific element comes into ...

Having trouble getting the on:dblclick event to trigger on a row within a list using S

I am currently using Sveltestrap and I am in need of a double click handler for a row: <ListGroupItem on:dblclick={handler(params)}> <Row> <Col><Icon name=........</Col> ... </Row> </ListGroupItem> Int ...

What is the proper location for inserting image copy code within my codebase?

I encountered an issue with using this code: copy('imgurl', 'images/covers/file.jpeg'); The code successfully copies an image URL to a file on my website when placed in a PHP page alone, but it fails to work within my actual code. He ...

What is the best way to transfer the value of a <span> element to a different <div> using jQuery or JavaScript

Is there a way to move or copy the price and insert it into the <div class="info"> using jQuery? The code I'm currently using is returning an unexpected result of "102030". jQuery(document).ready(function($) { $(document).ready ...

The Angular build is unsuccessful due to the presence of components from a separate Angular project

Whenever I execute ng build project1 --prod, the build fails and displays this error message: ERROR in : Cannot determine the module for class MyComponent in .../project2/app/my.component.ts! Add MyComponent to the NgModule to fix it.. Although the sol ...

a JavaScript file containing only a require statement with a list of dependencies and a function

I have a question regarding the implementation of the "require" statement in JavaScript. I am just starting to work with JS and Dojo, and I encountered an issue while developing a Plug-in for a website. The main Java class of the plugin makes a reference t ...