SO-63999595

by David Thomas

HTML

<form action="">
  <fieldset>
    <legend>How old are you?</legend>

    <select class="question" id="howold" name="ageRange">
      <option value="3">19 - 26</option>
      <option value="4">27 - 36</option>
      <option value="2">37 - 40</option>
      <option value="1">41+</option>
    </select>
  </fieldset>
  <fieldset>
    <legend>What's your relationship status?</legend>
    <select class="question" id="relationshipstatus" name="relationshipStatus">
      <option value="4">Single and excited to see what’s out there.</option>
      <option value="3">Recently single and emotionally destroyed.</option>
      <option value="2">Got some casual things on the go, not looking for anything too serious.</option>
      <option value="1">In a committed relationship and only taking this quiz for the lols.</option>
    </select>
  </fieldset>
  <fieldset>
    <legend>What is your location?</legend>
    <select class="question" id="location" name="location">
      <option value="4">Location Independent</option>
      <option value="3">London/The UK</option>
      <option value="2">Europe</option>
      <option value="1">Elsewhere</option>
    </select>

  </fieldset>
  <button type="button">Submit</button>
</form>

<div id="scoreDisplay"></div>

CSS

fieldset {
  margin: 0.5em 0;
}
legend {
  padding: 0 0.6em;
}
label {
  display: flex;
  gap: 0 0.6em;
  margin: 0.3em 0;
}

input + span {
  border-radius: 0.6em;
}

input:checked + span {
  color: limegreen;
}

JavaScript

const selectToRadio = (selectSelector) => {
    const selects = [...document.querySelectorAll(selectSelector)],
      input = document.createElement('input'),
      label = document.createElement('label'),
      span = document.createElement('span');

    input.type = 'radio';

    selects.forEach(
      (sel) => {
        let groupName = sel.name,
          options = [...sel.querySelectorAll('option')],
          fragment = document.createDocumentFragment();
        options.forEach(
          (opt) => {
            let inputClone = input.cloneNode(),
              labelClone = label.cloneNode(),
              spanClone = span.cloneNode();
            inputClone.name = groupName;
            inputClone.value = opt.value;
            inputClone.classList.add('answer');
            spanClone.textContent = opt.text;

            labelClone.append(inputClone, spanClone);
            fragment.append(labelClone);
          });
        sel.parentNode.insertBefore(fragment, sel);
        sel.remove();
      });
  },
  score = () => {
    const answers = [...document.querySelectorAll('.answer:checked')],
      result = answers
      						.map((el) => parseInt(el.value, 10))
      						.reduce((a, b) =>  a + b, 0);
      document.querySelector('#scoreDisplay').textContent = result;
    return result;
  };

selectToRadio('select');

document.querySelector('button').addEventListener('click', score);