Clearing my form inputs after submission

前端 未结 9 935
Happy的楠姐
Happy的楠姐 2020-11-30 04:25

I\'ve tried it a few different ways based on searches I\'ve done on the subject and for some reason I can\'t get it to work. I just want my text inputs and textarea to clear

相关标签:
9条回答
  • 2020-11-30 04:26

    since you are using jquery library, i would advise you utilize the reset() method.

    Firstly, add an id attribute to the form tag

    <form id='myForm'>
    

    Then on completion, clear your input fields as:

    $('#myForm')[0].reset();
    
    0 讨论(0)
  • 2020-11-30 04:27

    You can try this:

    function submitForm() {
      $('form[name="contact-form"]').submit();
      $('input[type="text"], textarea').val('');
    }
    

    This script needs jquery to be added on the page.

    0 讨论(0)
  • 2020-11-30 04:36

    Try this:

    function submitForm () {
        // your code
    
        $('form :input').attr('value', '');
    }
    
    0 讨论(0)
  • 2020-11-30 04:37
    var btnClear = document.querySelector('button');
    var inputs = document.querySelectorAll('input');
     
    btnClear.addEventListener('click', () => {
        inputs.forEach(input =>  input.value = '');
    });
    
    0 讨论(0)
  • 2020-11-30 04:46

    I used the following with jQuery $("#submitForm").val("");

    where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:

    function extractValue() { var value = $("#submitForm").val().trim(); console.log(value); };

    Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!

    0 讨论(0)
  • 2020-11-30 04:47

    The easiest way would be to set the value of the form element. If you're using jQuery (which I would highly recommend) you can do this easily with

    $('#element-id').val('')
    

    For all input elements in the form this may work (i've never tried it)

    $('#form-id').children('input').val('')
    

    Note that .children will only find input elements one level down. If you need to find grandchildren or such .find() should work.

    There may be a better way however this should work for you.

    0 讨论(0)
提交回复
热议问题