我已经开发了一个基本测验,并希望将测验的答案添加到一起以创建一个"得分"。根据分数,我将在确认页面上返回不同的结果。
以下是表单的基本示例:
<form id="quiz" method="post" name="quiz" action="url">
<label for="field1">Question 1</label>
<label><input name="question1" value="1" type="radio">Answer 1</label>
<label><input name="question1" value="4" type="radio">Answer 2</label>
<label><input name="question1" value="9" type="radio">Answer 3</label>
<label for="field2">Question 2</label>
<label><input name="question2" value="1" type="radio">Answer 1</label>
<label><input name="question2" value="4" type="radio">Answer 2</label>
<label><input name="question2" value="9" type="radio">Answer 3</label>
<label for="field3">Question 3</label>
<label><input name="question3" value="1" type="radio">Answer 1</label>
<label><input name="question3" value="4" type="radio">Answer 2</label>
<label><input name="question3" value="9" type="radio">Answer 3</label>
<input value="See your Results" type="submit">
</form>
我尝试构建一些javascript来将这些值添加到一起,但它甚至还没有开始工作 - 这是我的尝试,以防你感到好奇:
function generateScore(){
var maturityScore = document.forms[0].question1.value + document.forms[0].question2.value + document.forms[0].question1.value;
document.forms[0].maturityLevel.value = maturityScore;
}
document.forms[0].addEventListener('submit') = generateScore
有人能指出我正确的方向吗?很高兴使用javascript或jquery来做到这一点。请注意,我无法编辑表单html - 它是由我使用的MAP生成的(并且很丑陋 - 我上面发布的版本因可读性而被简化)。
谢谢!
答案 0 :(得分:1)
以下代码对您有所帮助,
$('#quiz').on('submit',function(){
var score = parseInt($('input[name=question1]:checked').val())+
parseInt($('input[name=question2]:checked').val())+
parseInt($('input[name=question3]:checked').val());
alert('submit'+score);
//score can be assigned to any field you need
//$('#maturityLevel').val(score);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="quiz" method="post" name="quiz" action="url">
<label for="field1">Question 1</label>
<label><input name="question1" value="1" type="radio">Answer 1</label>
<label><input name="question1" value="4" type="radio">Answer 2</label>
<label><input name="question1" value="9" type="radio">Answer 3</label>
<label for="field2">Question 2</label>
<label><input name="question2" value="1" type="radio">Answer 1</label>
<label><input name="question2" value="4" type="radio">Answer 2</label>
<label><input name="question2" value="9" type="radio">Answer 3</label>
<label for="field3">Question 3</label>
<label><input name="question3" value="1" type="radio">Answer 1</label>
<label><input name="question3" value="4" type="radio">Answer 2</label>
<label><input name="question3" value="9" type="radio">Answer 3</label>
<input value="See your Results" type="submit">
</form>
确保回答所有3个问题。否则,在使用parseInt
解析之前,您必须进行正确的验证。