我有一个使用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>
答案 0 :(得分:1)
您没有为您的提交按钮提供在事件侦听器中使用的ID提交,因此您必须使用.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>
答案 1 :(得分:-2)
如果您重新加载页面,则使用Cookie或会话/区域设置存储
document.cookie = "value = " + document.querySelector('[name="form_tools_form_id"]:checked').value + ";";
页面重新加载时,请检查页面是否为空
var x = document.cookie;
然后选中该复选框
document.querySelector('[name="form_tools_form_id"]:checked').checked = true;