javascript - 提交错误后记住单选选项
问题描述
我有一个使用带有几个单选按钮的 formtools 创建的联系表单。我需要让表单记住所选单选按钮上的选项,即使提交后出现错误。
var btn = document.getElementById('submit');
if (btn) {
btn.addEventListener('click', function(){
var dt = document.querySelector('[name="form_tools_form_id"]:checked').value;
alert('&option=' + dt)
});
}
<form action="check.php" id="contact" method="post">
<div class="radioboxes"><strong id="top-more">Options</strong><br>
<span class="othertopic" id="wwus"> <font>Please select one option</font></span>
<div id="top-wwus"><input id="topic_252" name="form_tools_form_id" type="radio" value="252"> <label for="topic_252">Recruitment</label><br>
<input id="topic_259" name="form_tools_form_id" type="radio" value="259"> <label for="topic_259">Requests</label><br>
<button name="submit" type="submit">Submit</button> </div> </div>
</form>
解决方案
您没有为您的提交按钮提供您在事件侦听器中使用的 id submit 并且您必须使用.preventDefault()
它以便它发出警报,否则它只会重定向。将值存储在 localStorage
var btn = document.getElementById('submit');
if (btn) {
btn.addEventListener('click', function(e){
console.log(dt)
e.preventDefault();
var dt = document.querySelector('[name="form_tools_form_id"]:checked').value;
alert('&option=' + dt)
localStorage.setItem('radio',dt);
});
}
<form action="check.php" id="contact" method="post">
<div class="radioboxes"><strong id="top-more">Options</strong><br>
<span class="othertopic" id="wwus"> <font>Please select one option</font></span>
<div id="top-wwus"><input id="topic_252" name="form_tools_form_id" type="radio" value="252"> <label for="topic_252">Recruitment</label><br>
<input id="topic_259" name="form_tools_form_id" type="radio" value="259"> <label for="topic_259">Requests</label><br>
<button name="submit" type="submit" id="submit">Submit</button> </div> </div>
</form>
推荐阅读
- git - GitKraken - 默认推送到远程源中的文件夹
- python - 在 2d + time Dask 堆栈上使用 openpiv 及时计算两个后续图像之间的运动
- jquery - jQuery 选项卡导航 - 禁用第一个和最后一个箭头
- excel - 将表格从 Word (.docx) 提取到 Excel
- r - ggplot 文本渲染不适用于某些字体
- python - AttributeError:'bytes'对象在python中从GCS读取.gz文件时没有属性'read'
- php - PHPpunit 测试随机失败
- sql - 如何在 Knex.js 中表达“小于或等于”关系
- python - pyspark - 如何保留模式
- excel - Split cells contents separated by comma using formulas