class RatingQuestion extends Element {
static styleKeys = ['root', 'label', 'ratingContainer', 'ratingButton', 'selectedRating', 'errorMessage'];
constructor({ id, text, maxRating = 5, ...otherProps }) {
super({ id, type: 'rating-question', ...otherProps });
this.text = text;
this.maxRating = maxRating;
}
generateHTML() {
const buttons = Array.from({ length: this.maxRating }, (_, i) =>
`<button class="rating-button" data-rating="${i + 1}">${i + 1}</button>`
).join('');
return `
<div class="rating-question" id="${this.id}-container">
<label for="${this.id}">${this.text}</label>
<div class="rating-container">${buttons}</div>
<div id="${this.id}-error" class="error-message"></div>
</div>
`;
}
attachEventListeners() {
const container = document.querySelector(`#${this.id}-container .rating-container`);
this.addEventListenerWithTracking(container, 'click', this.handleRatingClick.bind(this));
}
handleRatingClick(e) {
if (e.target.classList.contains('rating-button')) {
const rating = parseInt(e.target.dataset.rating);
this.setResponse(rating);
this.updateSelectedRating(rating);
}
}
updateSelectedRating(rating) {
const buttons = document.querySelectorAll(`#${this.id}-container .rating-button`);
buttons.forEach(button => {
if (parseInt(button.dataset.rating) <= rating) {
button.classList.add('selected');
} else {
button.classList.remove('selected');
}
});
}
validate(showError = false) {
const isValid = this.data.response !== undefined;
if (showError && !isValid) {
this.showValidationError('Please select a rating');
}
return isValid;
}
}