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

Error encountered when attempting to create an index in ElasticSearch due to

I am encountering an issue with the elasticsearch npm module while attempting to create an Index, resulting in a TypeError with the following message: Unable to build a path with those params. Supply at least index The code snippet I am using is as follo ...

IE z-index bug affecting Youtube videos

I've been experimenting with the YouTube API and I've included the following code snippet in http://jsfiddle.net/aaronk85/wapFR/. <div id="video-wrap2"></div> <div id="video-wrap"> <div id="play-video"></div> &l ...

The compatibility of IE9 with tables and the use of display: block

When optimizing my site for low-width mobile devices, I adjust the display property of various table elements such as tr, td, and th to block in order to stack them vertically. This technique helps wide tables to show all their content without overflowing ...

In the Redux framework, the reducer fails to identify the action object

I'm currently working on a React project using Redux. I've encountered an issue where my reducer is not recognizing the action type being sent to it, or even the action itself. The error message I am receiving is TypeError: Cannot read property & ...

Styling CSS for Centering a Heading on an Image's Center

Struggling to center an h3 heading in the middle of an image within a grid? Look no further, as I have 3 images across one row - four columns per image/heading. Check out the desired layout https://i.stack.imgur.com/8VFRt.png I've managed to center t ...

Unable to understand the reason behind why the button is not being displayed

I'm having trouble with my quiz app. I have a button to submit answers and move on to the next question, but whenever I try to place it within the div that contains the quiz, the button disappears. Can someone please help me figure out what's wro ...

Display the div only when the radio button has been selected

I have been attempting to tackle this issue for quite some time now, but unfortunately, I haven't had any success. My goal is to display a specific div on the webpage when a particular radio button is selected. While I have managed to achieve this by ...

Show whether the day is even or odd with the JavaScript getDay object

I'm currently working on a task where I need to show the text "Even Day" if the day of the month is 2, 4, 6..., and "Odd Day" for days such as 1, 3, 5, and so on. I attempted to achieve this by setting up an array linked to the getDay object, but unfo ...

Update my function to be asynchronous by changing async: false to async: true using JQuery and Ajax

I've created a function in a JavaScript class that accesses a PHP file to retrieve information from a database. Although this function works well, I attempted to set the property async: true, and it caused the function to stop working. (I received th ...

Error: Java Applet cannot be found

As I've come to understand, Java applets are no longer widely used and supported by most browsers. Could it be that my issue is simply due to lack of support? I'm currently testing my HTML file using Internet Explorer on Windows 10 with the follo ...

What is the method for selecting the desired month on a primeng calendar with multiple selection enabled?

I am looking for a solution to make my inline primeNg Calendar display the month of a specific date in the model, and when I remove dates from the model, I want it to show the current month. I have tried using defaultDate={{value}} and minDate={{value}}, a ...

degree of transparency when semi-transparent elements overlap

Imagine you have two <div> elements, one with an opacity of .5 and another overlaying it with the same opacity. What would be the combined opacity of the two? Interestingly, it's not as simple as, .5 × .5 or even, .5 + .5 How can this ...

Add formatting to a particular element without affecting elements within another element

Consider the following scenario: <input type='text' /> <br /> <iframe> <input type='text'> </iframe> With the style defined as: input[type='text'] { border: 1px solid black; } If you w ...

What are some ways to streamline this D3 script?

My CSV data displays pass rates by organisation for different years: org,org_cat,2004_passed,2004_total,2005_passed,2005_total,2006_passed,2006_total GSK,industry,35,100,45,100,55,100 I am using D3 and aiming to create a dictionary of organisations struc ...

What is the best way to adjust the height of a dropdown box in an angular application?

Is there a way to change the height of the scroll view? It seems too long for my liking, any advice? I attempted to adjust it using css but unfortunately, it didn't work out. The scroll view appears excessively lengthy as shown in the image below. ...

Incorporating geocoding functionality in an asp.net mvc project and looking to efficiently transfer latitude and longitude data from JavaScript to a controller function

UPDATED. Following your suggestions, I implemented the function as shown below: [HttpPost] public ActionResult populate_place(string lati, string longi) { list_placesModels list_place = new list_placesModels(); list_place.Latitude = lati; li ...

Function invoking React Hook

I'm a beginner to React JS and I've been learning by working on a project. I was creating a basic e-commerce UI with items and attempting to add items to a cart, but encountered an issue. The React Hook "useStateValue" is being called in the fun ...

What is the process for implementing AJAX in Django to send a model object and save it in the database without the need to reload the page?

I'm currently working on a Django project where I have implemented a favorite button feature on one of the pages. The idea is that when a user clicks on the button, it should return the model object and store it in another database for reference. Howe ...

Problem with <meta> tag occurring when initial-scale is adjusted

Initially, in the index.html file: <meta name="viewport" content="width=device-width, initial-scale=1" /> I decided to modify it to: <meta name="viewport" content="width=device-width, initial-scale=2" /> ...

What is the significance of default parameters in a JavaScript IIFE within a TypeScript module?

If I were to create a basic TypeScript module called test, it would appear as follows: module test { export class MyTest { name = "hello"; } } The resulting JavaScript generates an IIFE structured like this: var test; (function (test) { ...