Modify the css styles of an HTML element using TypeScript or JavaScript

I've implemented a star rating widget in an HTML form within my React JS application. The widget I am using can be found here. When a user clicks on one of the five stars, the user's information is saved to the server.

Currently, the selected stars remain highlighted even after the response comes back from the server. I would like to reset the stars to their unselected state for the user's next action. However, I'm unsure how to achieve this using TypeScript/Javascript. I've attempted to modify the code as follows:

let ratingElement = document.querySelectorAll("#ratingField > label");
if (ratingElement.length > 0) {
  for (let i = 0; i < ratingElement.length; i++) {
    ratingElement[i].style.color = "#ddd";
  }
}

The above code successfully resets the color, but there are other CSS properties like hover, checked, and unchecked that need to be reset as well. How can I include these properties to reset the stars to their initial stage?

Below is the CSS for the widget:

.rating {
  border: none;
  float: left;
}

/* Additional CSS properties here */

.rating > input:checked + label:hover, etc..

And here is the relevant HTML code:

<fieldset
    className="rating"
    style={{ marginLeft: 5, marginRight: 5 }}
    id="ratingField"
>
    <input type="radio" id="star5" name="rating" value="5" />
    <label onClick={() => this.shortlist(5)} className="full" htmlFor="star5" title="Awesome" />
    
    /* HTML for other stars here */
    
</fieldset>

If anyone has a solution or suggestions on how to accomplish this, it would be greatly appreciated! Thank you.

Answer №1

To gain insight into the initial state of your stars widget, use the browser inspector to analyze its classes and inline styles. It is advisable not to rely on inline styles for this purpose.

Once you have identified the initial classes, you can reset them using the following JavaScript code:

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

If there is a need to toggle a "checked" status, you can achieve it as shown below:

// Check
document.getElementById("checkbox").checked = true;

// Uncheck
document.getElementById("checkbox").checked = false;

In your specific scenario, you can uncheck an element by executing the following JavaScript command:

document.getElementById("star1").checked = false;

This method can be employed to uncheck any checked elements in the DOM.

Answer №2

  const selectedRating = document.querySelectorAll("#ratingField input[type=radio]:checked");

  selectedRating.forEach( function( element, index ) {
    console.log(element);
    element.checked = false;
  });

Click here to view the example - https://jsfiddle.net/4t56c9fq/8/

Avoid applying styles directly in JavaScript. Instead, toggle the "checked" attribute to true or false and let CSS handle the rest.

Answer №3

   <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> 
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
$('input[type="radio"]').next('label').css('background-position','0 -16px')
for(var i=1;i<=parseInt($(this).attr('name'));i++)
{
$('input[name="'+i+'"]').next('label').css('background-position','0 0')
}
})
$('#reset').click(function(){
$('input[type="radio"]').next('label').css('background-position','0 -16px')
})
})
</script>
<style>
.rating {
    overflow: hidden;
    display: inline-block;
}

.rating-input {
    float: right;
    width: 16px;
    height: 16px;
    padding: 0;
    margin: 0 0 0 -16px;
    opacity: 0;
}

.rating-star {
    cursor: pointer;
    position: relative;
    display: block;
    width: 16px;
    height: 16px;
    background: url('https://www.everythingfrontend.com/samples/star-rating/star.png') 0 -16px;
}

.rating-star:hover {
    background-position: 0 0;
}
</style>
<body>

       <span class="rating">
    <input type="radio" class="rating-input"
           id="rating-input-1-5" name="1">
    <label for="rating-input-1-5" class="rating-star"></label>
    <input type="radio" class="rating-input"
           id="rating-input-1-4" name="2">
    <label for="rating-input-1-4" class="rating-star"></label>
    <input type="radio" class="rating-input"
           id="rating-input-1-3" name="3">
    <label for="rating-input-1-3" class="rating-star"></label>
    <input type="radio" class="rating-input"
           id="rating-input-1-2" name="4">
    <label for="rating-input-1-2" class="rating-star"></label>
    <input type="radio" class="rating-input"
           id="rating-input-1-1" name="5">
    <label for="rating-input-1-1" class="rating-star"></label>
<input type="button" value="Reset" id="reset">
</span>
    </body>
    </html>

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

The name 'Map' cannot be located. Is it necessary to alter your target library?

After running the command tsc app.ts, an error occurs showing: Error TS2583: 'Map' is not recognized. Should the target library be changed? Consider updating the lib compiler option to es2015 or newer. I want the code to compile without any issu ...

What is the ideal amount of data to store in browser cache?

I am facing the challenge of loading thousands of user data records from a REST service, specifically user contacts in a contact-management system, and conducting a search on them. Unfortunately, the existing search functionality provided by the REST servi ...

Why is it that the default theme of Material UI lacks any stylization at all?

After experimenting with both Carbon Design for React (@carbon/react) and Material UI (@mui/material) in conjunction with Next.js, I encountered styling issues with the components. While they functioned correctly to some extent, there were noticeable discr ...

Errors encountered while running `npm install discord.js`

I am currently facing an issue while trying to install discord.js. Unfortunately, I keep encountering the following errors: npm ERR! cb() never called! npm ERR! This is an error with npm itself. Please report this error at: npm ERR! <https://npm.co ...

The most efficient method for documenting $.trigger in JavaScript/jQuery is through the use of JSD

When it comes to documenting in jsDuck, what is the optimal method for capturing the following event trigger: $(document).trigger('myCustomEvent'); ...

An easy guide to using Vue-Router to manipulate URL query parameters in Vue

I'm currently working on updating query parameters using Vue-router as I change input fields. My goal is to adjust the URL query parameters without navigating to a different page, but only modifying them on the current page. This is how I am approachi ...

Having issues with my CodePen React code and its ability to display my gradient background

I will provide detailed descriptions to help explain my issue. Link to CodePen: https://codepen.io/Yosharu/pen/morErw The problem I am facing is that my background (and some other CSS elements) are not loading properly in my code, resulting in a white bac ...

Using React Material UI checkboxes: Learn how to manipulate other checkboxes within a group by toggling a single checkbox

I've set up 3 checkboxes - Not Started, In Progress, and Completed - and I want only one to be checked at any given time. If 'Not Started' is initially checked, how can I make it uncheck automatically when I check 'Completed'? Th ...

Adding Extra Fields to PHP Email Form

Currently, I have an email form set up using PHP: <form method="post" action="contactus.php" autocomplete="off"> <label for="Name">Name:</label> <input type="text" name="Name" id="Name" maxlength="60" required/ ...

Issue with Google Chrome when entering time using HTML input type time

Hopefully I can figure out a solution for this issue. I am working on an AngularJS project and have the following HTML tag to select time: <input class="input-time" type='time' ng-model="dr.startTime"> The time is displayed in AM/PM forma ...

Is it possible to choose only half of the elements using the :nth-child selector in

Consider this code snippet: <ul> <li>Hello Universe</li> <li>Hello Universe</li> <li>Hello Universe</li> <li>Hello Universe</li> </ul> Can we select exactly half of the total elements by ...

The sequence of event handler executions in JavaScript

When multiple event handlers are attached to the same event on the same elements, how does the system determine the order in which they are executed? Although I came across this thread that focuses on click events, another discussion at this page points o ...

Sending the image's identification number as a parameter to a function and showing the total number

On a static page, I have the following HTML markup: <div class="middle-content"> <div class="white-div"> <div class="like-buttons"> <img id="1" src="up.png" onclick="onClick(true, this.id)" /> &l ...

Transitioning from Tailored CSS to Bootstrap

While I am experienced in HTML and CSS, I am new to working with Bootstrap. Here is a code snippet that works well but has a lot of custom CSS. Below you can see my HTML and CSS code. .container { padding: 150px; display: flex; align-items: center ...

Unable to retrieve embedded link using fetchText function in casperjs

Exploring the capabilities of Casperjs provides a valuable opportunity to test specific functions across different websites. The website used in this scenario serves as a tutorial illustration. An interesting challenge arises with an embed code that cann ...

Special character object properties in EJS

Currently, I am developing a website which involves using a language file structured like this: replace = { "x:a": "Hello", "x:b": "World!", "y:c.d": "Another text" } My goal is to pa ...

What is the process of implementing session storage in an AngularJS directive?

I am trying to save values in Angular session storage within an Angular directive, but I am facing an issue where I only receive NULL. Can anyone provide assistance? app.directive('myDirective', function (httpPostFactory) { return { restrict ...

What could be causing my data to undergo alterations when transitioning from a frontend form submission to a backend API?

In my experience with Next.js 13 and Prisma, I encountered a peculiar issue. I had set up a basic form to collect user information for an api request. Oddly enough, when I printed the data right before sending it, everything seemed fine. However, upon arri ...

Choose a random object from the array

I'm currently working on creating a function or an if condition that randomly selects one of three circles every second. The goal is to generate an animation where the circles move from the right side of the canvas to the left. Each second, a new cir ...

When clients format datetime, the default date value is sent on the form post

I'm attempting to utilize this particular example in order to correctly implement datetime formatting In my view model, I have a property for datetime public class MyViewModel { [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0 ...