Ways to add a CSS class to an ID that immediately follows

I've been working on an editable table using the HTML5 attribute contenteditable. Everything was going smoothly until I had an idea to highlight the cell that was just updated by adding a class called alert-danger from Bootstrap.

Once a cell is successfully updated, data is sent back to the parent page to inform the result div about the status. Currently, the status is displayed on top of the table, but I wanted to also add the class to the specific cell. So, I included

$("td[id="+cols3_key+"").addClass('alert-danger');
when the data is returned. I expected the latest cell to be applied with the alert-danger class, but unfortunately, it didn't work as intended. Here's my script:

Javascript

var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
    var cols3_key = $(this).attr("id") ;
    var value = $(this).text() ;
    $.post('inc/ajax.php' , cols3_key + "=" + value, function(data){
        if(data != ''){
            $("td[id="+cols3_key+"]").addClass('alert-danger');
            message_status.slideDown();
            message_status.text(data);
            //hide the message
            setTimeout(function(){message_status.slideUp()},3000);
        }
    });
});

The question is: How can I modify this line to target the cell that was just processed?

$("td[id="+cols3_key+"").addClass('alert-danger');

Best Regards,

Answer №1

Here is a suggestion for you: make sure to close the square bracket in your code.

$('td[id="+cols3_key+"]').addClass('alert-danger');

Alternatively, you can use the following code:

$('td[id$="cols3_key"]').addClass('alert-danger');

Answer №2

If you want to add the class 'alert-danger' using jQuery, you can simply use

$(this).addClass('alert-danger');
instead of
$("td[id="+cols3_key+"").addClass('alert-danger');

If you encounter issues with $(this) in the post callback, you can try using

$("td#"+cols3_key+"").addClass('alert-danger');

When using jQuery to access IDs, remember that you need to use the # symbol. For example, to access <td id='test'></td>, you would write

$('td#test').addClass('newClass');

Answer №3

You had a missing ], so instead of $("td[id="+cols3_key+"]") you can simplify it to $("#"+cols3_key)

Keep in mind, the first solution may require extra single quotes if the id contains special characters:

For example: $("td[id='"+cols3_key+"']")

The second approach will work regardless.

Alternatively, consider a more efficient method:

1) Place your ajax call in a function to handle specific elements for each call.

2) Directly reference the element without concerning yourself with the id.

Here's an example:

   var update = function($element){
        var value = $element.text();
        $.post('inc/ajax.php' , $element.attr('id') + "=" + value, function(data){
            if(data != ''){
                $element.addClass('alert-danger');
                message_status.slideDown();
                message_status.text(data);
                //hide the message
                setTimeout(function(){message_status.slideUp()},3000);
            }
        });
   }

var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
    update($(this));
});

Answer №4

At last,

With the generous assistance from all of you and the invaluable tip from @TrueBlueAussie, I have managed to find my way out of this predicament. Below is the complete script.

HTML

<h2 class="lead text-danger">HTML5 Inline Edit</h2>
<div id="status"></div>
<table class="table table-bordered table-striped">
    <tr>
        <td id="table_col1:1" contenteditable="true">
            content1
        </td>
        <td id="table_col1:2" contenteditable="true">
            content2
        </td>
        <td id="table_col1:3" contenteditable="true">
            content3
        </td>
    </tr>
</table>

CSS

    #status{
    background:#ff0000;
    border:solid 1px #ccc;
    border-radius:5px;
    color:#fff;
    display:none;
    padding:5px;
    width:100%;    
}

Javascript

$(window).load(function(){
        var message_status = $("#status");
        $("td[contenteditable=true]").blur(function(){
            var cols3_key = $(this).attr("id") ;
            var value = $(this).text() ;
            $.post('' , cols3_key + "=" + value, function(data){
                if(data != ''){
                    $('td[id="'+cols3_key+'"]').addClass('alert-danger');//this is the trick. I need a couple of single quotes here to express that I need a var not an id name

                    message_status.slideDown();
                    message_status.text(data);
                    //hide the message
                    setTimeout(function(){message_status.slideUp()},3000);
                    setTimeout(function(){$('td[id="'+cols3_key+'"]').removeClass('alert-danger')},3000);
                }
            });
        });
});

Check out the live demonstration - http://jsfiddle.net/nobuts/Lroqpk7x/9/

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

Having trouble utilizing Reactjs Pagination to navigate through the data

I'm currently working on implementing pagination for a list of 50 records, but I'm encountering an issue. Even though I have the code below, it only displays 10 records and I'm unaware of how to show the next set of 10 records until all 50 a ...

Unable to Retrieve Response from jQuery AJAX in a Function

Having some trouble with a jQuery AJAX function that is supposed to retrieve data from a file. I can't seem to get the function to return the actual value. Any suggestions? $(document).ready(function () { function fetchData() { ...

Limit the precision of decimal number output to a specific value

I need assistance with achieving the output 999999.35 in angular or javascript combined with html. I am looking to restrict the number of 9's to a maximum of 6 digits before the decimal point, and after 6 digits it should not accept any more digits. A ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

What could be causing the issue with the width: 100% not rendering correctly in this

I'm currently working on my footer, but I'm having trouble getting the width: 100% tag to work correctly. Here's a screenshot of what I mean: http://gyazo.com/9c23897cd7b9a74ca55ee9fb977f810c This is my CSS code: /*..Portfolio - Lars Beut ...

What could be causing my div to not appear when using jquery's show function?

I'm dealing with HTML code that looks like this: <div id="answerTypeSection" style="visibility: hidden"> <div class="row"> <div class="col-md-2">adfadfafasdfasdfas</div> </div> <label class="control-label"&g ...

"Exploring the best locations for storing CSS, JS, and image files in Spring

Having trouble figuring out where to place my public files. I attempted the solution mentioned in this thread on Stack Overflow but it didn't work for me. I've tried putting my public folder in various locations within the WEB-INF directory, but ...

Mastering the Art of Disabling buttons in Vue Based on Conditions

In my current project, I'm attempting to compare specific values of an initial object with an updated object in order to disable a button if they are the same. However, despite making changes, the button remains disabled: setDisabled() { return th ...

Adding dynamic content to CSS in Next.JS can be achieved by utilizing CSS-in-JS

Currently diving into the world of Next.JS, I've managed to grasp the concept of using getStaticProps to retrieve dynamic data from a headless CMS and integrate it into my JSX templates. However, I'm unsure about how to utilize this dynamic conte ...

Distinguishing between fonts on a website and Invsion (a tool utilized by designers and front end developers)

I am having difficulty achieving the exact look of our website font as intended by the designer. We have utilized Google's 'Source Sans Pro' font file. I have attempted various strategies: Using the font directly from Google [ Downloading ...

What is the best way to establish a maximum limit for a counter within an onclick event?

I'm struggling to figure out how to set a maximum limit for a counter in my onclick event. Can someone help me? What is the best way to add a max limit to the counter of an onclick event? Do I need to use an if statement? If yes, how should it be w ...

What is the best way to implement jQuery in Katalon to manipulate the DOM element?

While browsing through the jQuery documentation, I discovered that I can update a custom attribute of a div using the attr() method. Is there a way to invoke this jQuery function in Katalon to modify the DOM element before a specific ajax call? I'm w ...

A guide on transforming JSON data into HTML using Rails

I'm struggling with parsing JSON on a webpage. My webpage is designed with circles, where clicking on a circle triggers a call to the controller to retrieve specific information from a database and display it as graphs and text. The issue I'm fa ...

How can transitions be activated in Bootstrap 4 carousel?

Having an issue with my Bootstrap 4 carousel where I need to move 4 slides at a time. I have tried using the code below: $(this).carousel(4); However, the problem is that the carousel only jumps to that index without showing any transitions. Using $(this) ...

Exploring Typescript for Efficient Data Fetching

My main objective is to develop an application that can retrieve relevant data from a mySQL database, parse it properly, and display it on the page. To achieve this, I am leveraging Typescript and React. Here is a breakdown of the issue with the code: I h ...

Hover effects on the navigation bar combined with an image featuring a sub navigation menu

Looking to craft a dynamic navigation bar that switches out subcategory images on hover. (subcategories come pre-loaded with images) ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

Adding 7 days to a JavaScript date

Can you spot the bug in this script? I noticed that when I set my clock to 29/04/2011, it displays 36/4/2011 in the week input field! The correct date should actually be 6/5/2011 var d = new Date(); var curr_date = d.getDate(); var tomo_date = d.getDate( ...

Using two different typefaces to accommodate two distinct languages on a single webpage

Let me clarify my situation. I want to create a platform where users can input text in both Hebrew and English, regardless of the language of the website itself. This means that users could type in Hebrew on an English website and vice versa. My goal is to ...

Sophisticated Arrangement of Div Elements

Here's a scenario where Two divs are dynamically styled from the Database. I am attempting to align two divs in the layout shown here: https://i.stack.imgur.com/nYI7v.png Can this be achieved using Bootstrap's CSS class col-? In responsive mo ...