How to add a new row to a Kendo grid with a unique custom styling

I am looking for a way to insert new data into a Kendo grid, but I want the added row to have a custom class so that I can style it with a different background color. How can I achieve this? I have searched through all the documentation but couldn't find any relevant information.

    var dataSource = $('#grid').data('kendoGrid').dataSource;
    dataSource.insert(0, {
        "name":"ABC",
        "age": 99
    });

Answer №1

If you want to apply a new class to each row added dynamically, you can utilize the .addClass() method. However, this means that every time you paginate or add more rows, you will need to reapply the class.

To streamline this process, you can maintain a global array containing the UUIDs of all newly added rows and then reapply the class during the dataBound event.

For a demonstration, check out the Fiddle here

var newUUID = [];
$("#grid").kendoGrid({
    navigatable: true,
    filterable: true,
    pageable: {
        pageSize: 5,
        alwaysVisible: false,
        pageSizes: [5, 10, 20, 100]
    },
    dataBound: function(e) {
        $.each(newUUID, function(idx, ele) {
            if ($(ele).length != 0) {
                $(ele).addClass('newRow');
            }
        })
    }
});
$('#btn').on('click', function(e) {
    var dataSource = $('#grid').data('kendoGrid').dataSource;
    var x = dataSource.insert(0, {
        "name":"ABC",
        "age": 99
    });
    newUUID.push("[data-uid='" + x.uid + "']");
    $("[data-uid='" + x.uid + "']").addClass('newRow');
})

Answer №2

To find the newly added row, you can search for it using its UID and then apply a class to highlight the row.

If you are interested in learning about an alternative solution, check out this blog post: "Simple Row Coloring in a KendoUI Grid"

const sampleData = getSampleData();

$(document).ready(() => {
  $("#example-grid-wrapper").kendoGrid({
    dataSource: {
      data: sampleData.data,
      schema: {
        model: {
          fields: sampleData.fields
        }
      }
    },
    columns: sampleData.columns
  });

  setTimeout(insertNewRecordAfterOneSecond, 1000);
});

function insertNewRecordAfterOneSecond() {
  // Insert data
  let dataGrid = $('#example-grid-wrapper').data('kendoGrid');
  dataGrid.dataSource.insert(0, { id: 1, name: "Sam", location: "B", color: "blue", status: 0 });
  
  // Re-scan table and lookup newly added row.
  dataGrid = $('#example-grid-wrapper').data('kendoGrid');
  let dataView = dataGrid.dataSource.view();
 
  for (let i = 0; i < dataView.length; i++) {
    if (dataView[i].id === 1) {
      dataGrid.table.find("tr[data-uid='" + dataView[i].uid + "']").addClass("highlighted-row");
    }
  }
}

function getSampleData() {
  return {
    data : [
      { id: 2, name: "Grant",   location: "A", color: "green",  status: 1 },
      { id: 3, name: "Vaughan", location: "B", color: "red",    status: 0 },
      { id: 4, name: "David",   location: "A", color: "orange", status: 1 }
    ],
    fields : {
      id:       { type: "number" },
      name:     { type: "string" },
      location: { type: "string" },
      color:    { type: "string" }
    },
    columns : [
      { field: "id",       title: "ID",       width: "10%" },
      { field: "name",     title: "Name",     width: "30%" },
      { field: "location", title: "Location", width: "30%" },
      { field: "color",    title: "Color",    width: "20%" },
      { field: "status",   title: "Status",   width: "10%" }
    ]
  };
}
.highlighted-row {
  background: #FF0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />

<div id="example-grid-wrapper">
  <div id="example-grid"></div>
</div>


Another Approach

For an alternate method suggested by gaetanoM.

const sampleData = getSampleData();
var insertedUidList = [];

$(document).ready(() => {
  $("#example-grid").kendoGrid({
    dataSource: {
      data: sampleData.data,
      schema: {
        model: {
          fields: sampleData.fields
        }
      }
    },
    columns: sampleData.columns,
    // Suggested by gaetanoM
    dataBound: function(e) {
      $.each(insertedUidList, function(idx, uid) {
        // Re-apply class to existing rows.
        $(`tr[data-uid="${uid}"]`).addClass('highlighted-row');
      });
    }
  });

  // Insert two rows, one second apart.
  insertRowsWithDelay([
    { id: 0, name: "Joseph", location: "A", color: "yellow", status: 1 },
    { id: 1, name: "Sam", location: "B", color: "blue", status: 0 },
  ], 1000)
});

function insertRowsWithDelay(data, delayBetween) {
  if (data == null || data.length === 0) return;
  setTimeout(() => {
    insertNewRecord(data.pop());
    insertRowsWithDelay(data, delayBetween);
  }, 1000);
}

function insertNewRecord(record) {
  record = $('#example-grid').data('kendoGrid').dataSource.insert(0, record);
  insertedUidList.push(record.uid);
  $(`[data-uid="${record.uid}"]`).addClass('highlighted-row');
}

function getSampleData() {
  return {
    data : [
      { id: 2, name: "Grant",   location: "A", color: "green",  status: 1 },
      { id: 3, name: "Vaughan", location: "B", color: "red",    status: 0 },
      { id: 4, name: "David",   location: "A", color: "orange", status: 1 }
    ],
    fields : {
      id:       { type: "number" },
      name:     { type: "string" },
      location: { type: "string" },
      color:    { type: "string" }
    },
    columns : [
      { field: "id",       title: "ID",       width: "10%" },
      { field: "name",     title: "Name",     width: "30%" },
      { field: "location", title: "Location", width: "30%" },
      { field: "color",    title: "Color",    width: "20%" },
      { field: "status",   title: "Status",   width: "10%" }
    ]
  };
}
.highlighted-row {
  background: #FF0; /* Highlight row yellow */
}
.highlighted-row.k-alt {
  background: #DD0; /* Apply different styling to highlighted row */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />

<div id="example-grid"></div>

Answer №3

If you want to implement a databound function for the grid, you can use the following code:

    function onDataBound(e) {
      var dataSource = $("#GridName").data("kendoGrid").dataSource;
      var data = dataSource.data();
            $.each(data, function (index, rowItem) {
               if (data.length > 0) {
                  var rows = e.sender.tbody.children();
                   var row = $(rows[index]);
                   if (data[index].name == "ABC" ) {
                      row.addClass("NameColor");
                     }
                 }
              });
     }
<style>
    .NameColor {
        background-color: black;
    }

</style>

You can test this implementation by using it like this.

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 more efficient method for replacing all attributes on cloned elements?

While this code does the job, I can't help but feel like it's a bit outdated. I'm not very experienced with JS/JQuery and only use them when necessary. My approach involves cloning an element and then replacing all of its attributes with on ...

Google Extension PHP Plugin

Is it feasible to integrate a PHP file into a Google Extension for Chrome? I've been exploring the idea of creating an extension and most resources only mention HTML, CSS, and JavaScript. Any guidance on using PHP in the extension would be highly valu ...

Waiting for a function to finish within a nested function in JavaScript

I'm facing a simple issue that I'm struggling to solve. I have two functions and an object in JavaScript (Node.js) structured like this: var auxmap = new Map(); function one() { for(var i...) { //initialize the map and do something tw ...

Using jQuery to retrieve the TD value

I'm attempting to retrieve the TD value using the Value attribute.... Let's say I have the following HTML markup: <td nowrap="nowrap" value="FO2180TL" class="colPadding" id="salesOrderNumber1">bla bla </td> So, I tried this- v ...

Can you provide guidance on how to successfully transfer an array of JSON objects from the script section of an HTML file to the JavaScript

My webpage contains an array of JSON objects that I need to send to the server. The array, stored in a variable called results, appears normal when checked in the console before trying to POST it. Here is a sample of the data: 0: {id: 02934, uName: "Ben", ...

What is the best way to dynamically insert an object into a field name in react-final-form?

When using the react-final-form component, you can expect the following result: <Field name="answers[0].name" component="input" type="radio" value="0" /> { answers: [ { name: 'value' } ] ...

handling null data in a jquery ajax callback

I've been working with knockout.js to bind data and making jQuery ajax calls to a restful service that returns JSON data. I've tried multiple approaches but can't seem to figure out the correct syntax for the call. Every time the callback fi ...

receiving a pair of components instead of just one

Here is the code for router.js: import React from 'react'; import { Route } from 'react-router-dom'; import CommentList from './containers/commentview'; import CommentDetalList from './containers/commentdetailview'; ...

AngularJS - development of a service entity

After deliberating between posting in the Angular mailing list or seeking assistance from the JavaScript community, I have decided that this is more of a JavaScript question. Hopefully, the knowledgeable individuals on Stack Overflow can provide a quicker ...

Utilize the JavaScript .send function to pass an array

Can an array be passed to a PHP page using the code below? If not, what modifications are needed in the code? function ajax_post(){ var hr = new XMLHttpRequest(); hr.open("POST", "get_numbers.php", true); hr.setRequestHeader("Content-type", "a ...

What are the best techniques for using jQuery to manipulate an HTML form that contains nested elements?

I have a scenario where I need to dynamically generate mini-forms within an empty form based on certain conditions. For instance, imagine a form that gathers information about restaurants such as their names and locations. Depending on the number of restau ...

Personalized validation messages with jQuery

I am currently working on a contact form using jQuery, but I am facing challenges in displaying my custom validation messages. Instead of showing the message I specified, it only displays a small popup with the generic message: "Please fill in the form". I ...

Setting the AJAX URL in CakePHP 1.2 for multiple routes

Greetings! I am currently making updates to an outdated website that was originally created using cakephp1.2. Let me show you a glimpse of the view structure: view structure This website was initially designed to allow users to access the content of the a ...

Removing the root component in ReactJS can be done on specific pages by implementing

Is there a way to remove the <header/> and <footer/> components from my signup.js and signin.js pages without altering the root index.js file? Presently, the root index.js file looks like this: class Template extends React.Component { render( ...

Exploring how to locate an item in an array using its id with Underscore

Here is an array of objects showcasing equipment images: var jsonarray = [{ "id": "6", "equipment_img": "http://xxx:9696/XXX/images (1)_410.jpg" }, { "id": "7", "equipment_img": "http://xxx:9696/XXX/5.jpg" }, { "id": "8", "equipmen ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

There seems to be an error with cheeriojs regarding the initialization of exports.load

I am currently using cheeriojs for web scraping, but I am encountering an issue after loading the body into cheerio. Although the body appears to be well-formatted HTML code, I am receiving errors such as exports.load.initialize. This is preventing me fr ...

Unlock real-time alerts with the power of JavaScript and PHP!

I am currently working on enhancing my skills in javascript. I have a basic idea of what I want to achieve. My goal is to create an automated javascript function that accesses a php page. This php page will create an array of new notifications for the ja ...

Looking for a logo placed in the center with a top fixed navigation using Bootstrap

I am in need of a Centered Logo using Bootstrap fixed top navigation. The goal is to have the brand centered within the navigation. Check out my Sample Fiddle .LandPageNavLinks { list-style-type:none; margin:0; padding:0; } .LandPageNavLin ...

Having trouble with changing the class using Jquery click function

Originally, I had the code in an ASP.Net project, but to troubleshoot, I moved it to a separate web server. However, I am still unable to switch between the tab panes with the buttons. Any assistance in debugging this issue would be greatly appreciated. S ...