简体   繁体   中英

How to clear the pre-post values of form fields after submit, and fill the form again with the blank fields

This is my website http://exmaple.com/schedule-appointment/ where I have applied a script to clear the form fields values after submit. Basically when you book the appointment for the first time and done. You again come back on the same page for another appointment then you will see that all the fields of form already filled. So I do not want this happens on the live website. I have used a script to clear the fields but it is working on firebug console but not worked on the live website. Is there anything wrong what I did earlier, Below is my script that I have used and committed to the server.

<script type="text/javascript">
jQuery(document).ready(function (){
    jQuery('.form-horizontal').each(function(){ 
        alert("hello");
        this.reset(); 
    }); 
});
</script>

Please help how we can clear the form fields for the second time to book an appointment.

Many thanks!

Possibly caused by browser autocomplete? Try adding autocomplete="off" to your form tag.

https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion

<!DOCTYPE html>
<html>
  <head>
    <title>your page</title>
  </head>
  <body>
    <form action="">
      <div>
        <input type="text" id="sngl_txt">
      </div>
      <div>
        <textarea id="mlt_txt"></textarea>
      </div>
      <div>
        <select id="selection">
          <option value="">no selection (default)</option>
          <option value="1">option 1</option>
          <!-- and so on -->
        </select>
      </div>

      <div>
        <button type="button" id="rst_btn">reset form</button>
      </div>
    </form>
  </body>

<script type="text/javascript" src="link.to.your.jquery.library"></script>
<script type="text/javascript">

$(document).on('ready', function(){

  // prepare with sample values
  $('form').find('#sngl_txt').val('sample text');
  $('form').find('#mlt_txt').val('Lorem ipsum ....");
  $('form').find('#selection').val(1);

  var reset = function(){
    $('form').find('input, textarea, select').val('');
  }


  $('form').find('#rst_btn').on('click', reset);

  // or
  // $('form').find('#rst_btn').on('click', function(){
  //   reset();
  // });
  // if you don't want to use the reset funtion as listener

});

</script>
</html>

i know in this sample a simple button type="reset works too", but i often have to work with customized controls and i had to set the value to an empty string by hand.

what you can try is $('form').reset() and not $('.form-horizontal').reset() , the effect will be the same a reset

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM