Is there a way to refresh a Thymeleaf table without reloading the entire page?

Displayed below is both my HTML and JavaScript code, utilizing Thymeleaf to dynamically render table content. The button's functionality changes based on the notified value - if it's 1, the button is disabled with a modified CSS style. When the value is different, users can click the button. Upon clicking, the worksomething() function is triggered. My objective is for a successful response to disable the button associated with the selected ID and update its CSS without reloading the page, mirroring the behavior when the notified value is 1.

function worksomething(orderId){
  $.ajax({
    url  : "/myirl/"+ orderId,
    type : 'GET',
    contentType : "application/json",
    dataType : "JSON",
    success: function (response) {
      alert("Disabled");
    },
    error: function (response) {
      alert("work Failed");
    }
  });
}
<table class="table" data-table ="all-orders" id="all-orders" role="grid">
     <thead>
        <tr>
            <th>ID</th>
            <th>Actions</th>
        </tr>
     </thead>
     <tbody>
        <tr th:each="order : ${orders}">
            <td>
                <button class="btn btn-link" th:text="${order?.orderId}"></button>
            </td>
            <td>
                <button type="button" class="btn btn-warning btn-md"
                            th:disabled="${(order?.notified)} == 1"
                            th:style="${(order?.notified) == 1 ? 'background-color: red;border-color:red;' : 'background-color: #eea236;border-color:#eea236;'}"
                            th:onclick="|worksomething('${order?.orderId}')|">
                Change</button>
            </td>
      </tr>
    </tbody>
</table>

Answer №1

Utilizing a JavaScript library like jQuery to connect JS events with HTML is recommended for enhancing code readability.

<table class="table" data-table ="all-orders" id="all-orders" role="grid">
     <thead>
        <tr>
            <th>ID</th>
            <th>Actions</th>
        </tr>
     </thead>
     <tbody>
        <tr th:each="order : ${orders}">
            <td>
                <button class="btn btn-link" th:text="${order?.orderId}"></button>
            </td>
            <td>
                <button type="button" class="btn btn-warning btn-md change-btn"
                            th:disabled="${(order?.notified)} == 1"
                            th:style="${(order?.notified) == 1 ? 'background-color: red;border-color:red;' : 'background-color: #eea236;border-color:#eea236;'}"
                   the:attrs="order-id=${order?.orderId}">
                Change</button>
            </td>
      </tr>
    </tbody>
</table>

To achieve this using jQuery, you can implement the following JavaScript code:

$(function(){
  $(".change-btn").on('click', function(event){
    var ordered = $(this).attr('order-id');
    var myButton = $(this);
    $.ajax({
      url  : "/myirl/"+ orderId,
      type : 'GET',
      contentType : "application/json",
      dataType : "JSON",
      success: function (response) {
        alert("Disabled");
        $(myButton).prop('disabled', true);
        //to remove disabled:
        //$(myButton).prop('disabled', false);
      },
      error: function (response) {
        alert("work Failed");
      }
    });
  });
});

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

What is the best way to delete a CSS class from a specific element in a list using React?

I need to implement a functionality in React that removes a specific CSS class from an item when clicking on that item's button, triggering the appearance of a menu. Here is my code snippet. import "./Homepage.css" import React, { useState, ...

Uh oh! An error occurred when trying to submit the form, indicating that "quotesCollection is not defined" in Mongodb Atlas

Displayed below is my server.js file code, along with the error message displayed in the browser post clicking the Submit button. const express = require('express'); const bodyParser = require('body-parser'); const MongoClient = require ...

The absence of localStorage is causing an error: ReferenceError - localStorage is not defined within the Utils directory in nextjs

I've been trying to encrypt my localstorage data, and although it successfully encrypts, I'm encountering an error. Here's the code snippet (./src/utils/secureLocalStorage.js): import SecureStorage from 'secure-web-storage' import ...

Selecting the current date in a Jquery Datepicker using PHPUnit WebDriver Selenium and PHP

Check out this demo of our datepicker: ( Located in the bottom left corner ) $search21 = $this->webDriver->findElement(WebDriverBy::id('csandbox-container')); $search21->click(); // Clicking opens the datepicker. // Now, how do I ...

Creating a collaborative storage space within a MERN project folder

Currently, I am developing an application using the MERN stack. The structure of my project repository includes both backend and frontend components: my-project/ ├── backend/ │ │ │ . │ . │ └── package.json ├── fronten ...

Attempting to direct Heroku towards the index.html file

I am currently using Heroku for deploying my website with node.js. I noticed that in the index.js file, the tutorial has "Hello World" in the response.end method, but I would like it to display my index.html file instead. Is there a way to achieve this? ...

In React, the loadend event of the XMLHttpRequestUpload fires instantly irrespective of the ongoing upload progress

Whenever I invoke this function within my React application (anticipating it within a try...catch block), I notice that the onloadend and onprogress events are triggered immediately even though the actual uploading process takes some time (I can monitor it ...

Click on an element using jQuery to apply a specific class to all other similar

I am looking to dynamically add a class to a DIV after clicking on an A element with the same class. Here is an example: <ul> <li><a href="#1" class="test1">1</a></li> <li><a href="#2" class="test2">2</a>< ...

Switching from real pixels to CSS pixels

The details provided in Mozilla's documentation on elementFromPoint clarify that the coordinates are specified in "CSS pixels" rather than physical pixels. This raises a question about what exactly CSS pixels entail. Many assume that a pixel in CSS is ...

Best method to run AJAX-retrieved JavaScript code without relying on jQuery

Imagine receiving a response to an AJAX data load request containing a combination of JavaScript and HTML, like this: <script>window.alert('Hello World!');</script> <p>This is a paragraph. Lorem ipsum dolor sit amet...</p> ...

Tips for positioning a div element within the body of a webpage to maintain a predetermined height and width

Currently, I am developing a single-page application using AngularJS. I have specific routes in mind where I want to introduce new HTML templates. To accomplish this, I have created a container labeled with the ID #main positioned between two navbars (he ...

Incorporate href along with ng-click for improved functionality

I need a link that will call a $scope-function when clicked, which will then display another view. I also want the user to be able to right-click on the link and open it in a new window or bookmark it. Unfortunately, the current html code is not worki ...

Unable to retrieve data from local file using ajax

While delving into the world of AJAX, I encountered an issue when trying to fetch data from a local file. An error related to CORS popped up, despite my attempts to solve it by installing the 'allow-access-control-origin' plugin. Any assistance w ...

The problem arose when the jquery onchange event was not triggered after dynamically inserting a

Here is my current setup: somefile.php $("document").ready(function() { var handler = function(data) { var JsDiv = document.getElementById("somediv"); JsDiv.innerHTML = data; }; $("input[type='checkbox']").change( function() ...

Managing dates in Coordinated Universal Time (UTC) on the

Let's address the current situation: The occurred_at dates are stored in UTC in the database. I am developing an API method using Laravel to retrieve records with these occurred_at fields. The JSON output currently displays the dates in a string form ...

The jQuery code is executing before the AJAX request is fully processed

$("form#go").submit(function(){ var $this = $(this); var btn = $this.find("button"); btn.text("Searching").attr('disabled','disabled'); $.ajax({ url: type: data: dataType: ...

Error encountered in Webpack 4 when trying to compile node modules CSS file: Unexpected .(dot) token

I am currently in the process of transitioning my React project from client-side rendering to server-side rendering. Unfortunately, I have encountered an issue with my webpack configuration for CSS that was working perfectly fine in my original project (c ...

Embed JavaScript within the Material-UI style components

I was hoping to incorporate some conditional logic within my MUI styles Currently, I am using inline styles which are functional <div className={classes.form} style={{alignItems: ((Code.length>10 || Description.length>100) ? 'start' : & ...

Using CSS3 keyframe animations to stop and remain on the final frame

I'm having trouble getting a CSS3 keyframe animation to stick at the last frame after it has completed. I thought setting animation-fill-mode to forwards would work, but it doesn't seem to be doing anything. .animatedSprite { .animation-nam ...

Menu options disappearing upon clicking within the container area

Every time I click inside the dropdown menus, they unexpectedly close. This issue is persistent in both the Login menu and the nav bar. Although I’m not a seasoned web developer, I suspect it’s just a simple error that I’ve been overlooking all day ...