首页 > 解决方案 > 提交错误后记住单选选项

问题描述

我有一个使用带有几个单选按钮的 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> 

标签: javascripthtml

解决方案


您没有为您的提交按钮提供您在事件侦听器中使用的 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> 


推荐阅读