JSFiddle - React, Tailwind, and code Playground

by doctor23

HTML

<div id="rating"></div>
<input id="rating-value" type="number" value="5.5" min="0" max="9" step="0.5">

JavaScript

const ratingElem = document.querySelector('#rating');
const inputElem = document.querySelector('#rating-value');

inputElem.addEventListener('change', _ => setRating(ratingElem, inputElem.value));

function setRating(elem, n) {
  const minValue = 0;
  const maxValue = 9;
  const filledImage = '<img src="http://new.fm-apeks.ru/image/catalog/description/three.png " alt="">';
  const halfEmptyImage = '<img src="http://new.fm-apeks.ru/image/catalog/description/two.png " alt="">';
  const emptyImage = '<img src="http://new.fm-apeks.ru/image/catalog/description/one.png " alt="">';
  n = (n < minValue) ? minValue : n;
  n = (n > maxValue) ? maxValue : n;
  n = Math.trunc(n * 2);
  const filledCount = Math.trunc(n / 2);
  const halfEmptyCount = n % 2;
  const emptyCount = maxValue - (filledCount + halfEmptyCount);
  const rating = filledImage.repeat(filledCount) + halfEmptyImage.repeat(halfEmptyCount) + emptyImage.repeat(emptyCount);
  ratingElem.innerHTML = rating;
}