M
M
Max2019-11-04 17:27:47
JavaScript
Max, 2019-11-04 17:27:47

Create a test/questionnaire in JS?

Well, the so-called “journal” questionnaire test. The result should be a single number depending on the checkboxes selected.
I already found the answer on the forum, but something does not work ... can someone help with the code? I click on the result, but nothing happens ...

<html>
<head>
<script language="JavaScript">
var btnResutl = document.getElementById('btnResutl');
var resultFild = document.getElementById('resultFild');
var inputFild = document.getElementsByTagName('input');
btnResutl.addEventListener('click', function(){
    let resultedInputs = document.querySelectorAll("input[type='radio']:checked");
    let result = 0;
    Array.prototype.map.call(resultedInputs, (el)=>{
      result += parseInt(el.dataset.value);
    });
    console.log(result);
    resultFild.innerHTML = result + ' баллов'
});</script>
</head>

<body>
<h4>Your test</h4>
<h3>Try yourself</h3>
<div class="question">
  <p>Do you have..</p>
  <input type="radio" value= "1" name="r1" id="Answer" data-value='1'><label>Home</label>
  <input type="radio" name="r1" id="Answer" data-value='2'><label>Sity</label>
  <input type="radio" name="r1" id="Answer" data-value='3'><label>Advanture</label>
</div>

<div class="question">
  <p>Do you have..</p>
  <input type="radio" value= "1" name="r2" id="Answer" data-value='4'><label>Home</label>
  <input type="radio" name="r2" id="Answer" data-value='5'><label>Sity</label>
  <input type="radio" name="r2" id="Answer" data-value='6'><label>Advanture</label>
</div>

<div class="question">
  <p>Do you have..</p>
  <input type="radio" name="r3" id="Answer" data-value='7'><label>Home</label>
  <input type="radio" name="r3" id="Answer" data-value='8'><label>Sity</label>
  <input type="radio" name="r3" id="Answer" data-value='9'><label>Advanture</label>
</div>

<div class="question">
  <p>Do you have..</p>
  <input type="radio" name="r4" id="Answer" data-value='10'><label>Home</label>
  <input type="radio" name="r4" id="Answer" data-value='11'><label>Sity</label>
  <input type="radio" name="r4" id="Answer" data-value='12'><label>Advanture</label>
</div>
<button id="btnResutl">Result</button>
<div id="resultFild"></div>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Chuprik, 2019-11-04
@drampeer

The JS code needs to "see" the html code it's working with. If you have JS in the head, then it starts executing even before the rest of the DOM is loaded, which is why it does not work as it should. Move JS to the end of the file.
PS: I didn't even look at the rest.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question