Задать вопрос
@Minusator

Как сложить radio и checkbox и вывести итоговой цифрой в форме на jquery?

Есть форма:

<form id="quiz">
<div class="checkbox-block">
    <div class="quiz__answer--txt__wrap">
        <label class="quiz__answer--txt">
            <input type="checkbox" name="q2[]" rel="10000">
            <p> Чекбокс 1 </p>
        </label>
    </div>
    <div class="quiz__answer--txt__wrap">
        <label class="quiz__answer--txt">
            <input type="checkbox" name="q2[]" rel="20000">
            <p> Чекбокс 2 </p>
        </label>
    </div>
    <div class="quiz__answer--txt__wrap">
        <label class="quiz__answer--txt">
            <input type="checkbox" name="q2[]" rel="10000">
            <p> Чекбокс 3 </p>
        </label>
    </div>
</div>

<div class="radio-block-1">
    <div class="quiz__answer--txt__wrap">
        <label class="quiz__answer--txt">
            <input type="radio" name="q3" rel="10000">
            <p> Радио 1 </p>
        </label>
    </div>
    <div class="quiz__answer--txt__wrap">
        <label class="quiz__answer--txt">
            <input type="radio" name="q3" rel="20000">
            <p> Радио 2 </p>
        </label>
    </div>
   
</div>

<div class="radio-block-2">
    <div class="quiz__answer--txt__wrap">
        <label class="quiz__answer--txt">
            <input type="radio" name="q4" rel="10000">
            <p> Радио 1 </p>
        </label>
    </div>
    <div class="quiz__answer--txt__wrap">
        <label class="quiz__answer--txt">
            <input type="radio" name="q4" rel="20000">
            <p> Радио 2 </p>
        </label>
    </div>
   
</div>
<span class="result"></span>
</form>

Необходимо просуммировать отмеченные чекбоксы из атрибутов rel + значения из атрибута rel в радио блока radio-block-1 + значения атрибута rel в радио блока radio-block-2 = итоговое значение всех сложений.

Как это сделать на jquery 3.6.0?
  • Вопрос задан
  • 124 просмотра
Подписаться 1 Средний Комментировать
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
Функция суммирования:

function sum(data, key = n => n) {
  const getVal = key instanceof Function ? key : n => n[key];
  let result = 0;

  for (const n of data) {
    result += getVal(n);
  }

  return result;
}

У формы надо слушать событие change:

const form = document.querySelector('form');
const result = form.querySelector('.result');
form.addEventListener('change', onChange);
form.dispatchEvent(new Event('change'));

Как может выглядеть обработчик:

function onChange() {
  result.textContent = sum(
    this.querySelectorAll(':checked'),
    n => +n.getAttribute('rel')
  );
}

// или

function onChange(e) {
  result.innerText = sum(
    e.currentTarget.elements,
    n => n.attributes.rel.value * n.checked
  );
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы