如何解决Parsint查询始终显示为NaN
使用下面的代码,我得到“您的分数是NaN”,我不知道为什么。最终代码将汇总测验中的所有问题。
在浏览器中,我可以看到无线电的值被正确拾取,并且我使用parseint将其转换为数字。但显然有什么问题
感谢您的帮助。
<form id="form1" method="post">
<br><strong><label for="benefit1">From the list below select those that are ISO27001 Benefits
</strong></span></label><br><br>
<input type="checkbox" name="benefit1" value="1" /> Helps you to comply with other regulations</p>
<input type="checkbox" name="benefit2" value="1" /> Keeps confidential information secure</p>
<input type="checkbox" name="benefit3" value="1" /> Protects the company,assets,shareholders and
directors</p>
<input type="checkbox" name="benefit4" value="1" /> Allows for secure exchange of information</p>
<input type="checkbox" name="benefit5" value="1" /> Manages and minimises risk exposure</p>
<br><input id="Q4PrevBut" type="button" Value="Previous Question">
<input id="Q4NextBut" type="button" Value="Next Question">
</form>
</div>
<div class ="Q5">
<p>Your score is: <span id="grade"></span></p>
<script>
var a1 = parseInt($("input[name='benefit1']:checked").val());
var result = a1;
document.getElementById("grade").innerHTML = result;
</script>
</div>
</body>
</html>
解决方法
您的查询$(“ input [name ='benefit1']:checked”)。val()仅在选中时会获取name ='benefit1'的输入元素,但是在加载页面时,脚本会立即执行没有选中任何复选框。因此,此$(“ input [name ='benefit1']:checked”)查询将不会检索任何元素。
我的建议是在每个复选框元素上附加onclick事件,并调用处理该事件的函数。
像这样的东西:<input type="checkbox" name="benefit1" value="1" onclick="handleCheckbox(this)"/>
handleCheckbox函数:
function handleCheckbox(checkbox){
result = parseInt(this.value);
...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。