I want to create a function that can switch favorites per row using a star icon.

1 Answer 126 Views
Button Data Source Grid
Aeong
Top achievements
Rank 1
Iron
Aeong asked on 03 Aug 2023, 07:16 AM

Hello, I am studying a lot because I am using Kendo for JQuery for the first time in this project.

Currently, I am creating a function that registers a favorite for each row of data, and I need to create it as shown in the picture.

The favorite column is assigned a Y/N cutoff value, and the icon changes accordingly.

And when the icon is clicked, the icon should change if the favorite status is successfully switched through ajax communication.

Thanks a lot for all your help!

Ruchika
Top achievements
Rank 1
Iron
commented on 03 Aug 2023, 11:55 AM | edited

.

1 Answer, 1 is accepted

Sort by
0
Accepted
Ruchika
Top achievements
Rank 1
Iron
answered on 03 Aug 2023, 12:00 PM

avaScript
function registerFavorite(row, isFavorite) {
  // Get the favorite column.
  var favoriteColumn = row.find(".favorite-column");

  // Get the icon element.
  var iconElement = favoriteColumn.find(".icon");

  // If the favorite status is not yet set, set it to the default value.
  if (isFavorite === undefined) {
    isFavorite = false;
  }

  // Change the icon according to the favorite status.
  if (isFavorite) {
    iconElement.attr("class", "fa fa-heart");
  } else {
    iconElement.attr("class", "fa fa-heart-o");
  }

  // Send an Ajax request to update the favorite status in the database.
  $.ajax({
    url: "/api/favorites",
    method: "POST",
    data: {
      id: row.data("id"),
      isFavorite: isFavorite,
    },
  });
}

$(document).on("click", ".favorite-column", function() {
  // Get the current favorite status.
  var isFavorite = $(this).find(".icon").hasClass("fa-heart");

  // Register the favorite with the opposite status.
  registerFavorite($(this).closest("tr"), !isFavorite);
});

This code will first get the favorite column and the icon element for the current row. Then, it will check the current favorite status and change the icon accordingly. Finally, it will send an Ajax request to update the favorite status in the database.

To use this code, you will need to add the following CSS classes to your favorite column:


.favorite-column {
  cursor: pointer;
}

.fa-heart {
  color: red;
}

.fa-heart-o {
  color: black;
}

You will also need to create a /api/favorites endpoint in your API to update the favorite status in the database

Aeong
Top achievements
Rank 1
Iron
commented on 07 Aug 2023, 02:17 AM

Sorry for the late reply. You have been of great help to me!
Tags
Button Data Source Grid
Asked by
Aeong
Top achievements
Rank 1
Iron
Answers by
Ruchika
Top achievements
Rank 1
Iron
Share this question
or