Form input fields is cleared including submit value also

html clear form after submit
javascript clear input field on click
onclick clear input field javascript
javascript reset form after submit
onclick clear input field jquery
clear form after submit php
javascript clear textbox on button click
javascript reset input field

I working with form validations I want to clear fields after submitting form its working fine but <input type="submit" value="submit">is also being clear but i want only input fields should be cleared. i tried with reset(); also but without adding reset().In my code fields is cleared Here what I'm doing wrong. Can anyone suggest me how I solve this problem?

Before submitting form

After submit form

var Validator = function(formObject) {
    this.form = $(formObject);
   var Elements = {
        text: {
            reg: /^[a-zA-Z]{2,20}$/,
            require : true,
            error: "Not a valid name.",
        },

        email: {
            reg: /^[a-z-0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
            error: "Not a valid e-mail address.",
        },
        phone: {
            reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
            error: "Not a valid number.",
        },

        message: {
            reg: /^(?!\s*$).+/,
            error: "Message field cannot be empty.",
        },
        gender: {
          error: "gender is required",
        },
        selectOption: {
          error: "this field is required",
          required: true
      }
    };

    var handleError = function(element, message) {
        element.addClass('input-error');
        var $err_msg = element.parent('div');
        $err_msg.find('.error').remove();

        var error = $('<div class="error"></div>').text(message);
        error.appendTo($err_msg);
        console.log(element);


      element.on('keypress change', function() {
            $(error).fadeOut(1000, function() {
            console.log(element);
            element.removeClass('input-error');
            });
        });

    };

    this.validate = function() {
      var errorCount = 0;

      this.form.find("select").each(function(index, field){
         var type = $(field).data("validation");
            var validation = Elements[type];
          if($(field).val() == "") {
            errorCount++;                       
            handleError($(field), validation.error);
          }
      });

        this.form.find("input, textarea").each(function(index, field){
            var type = $(field).data("validation");
            var validation = Elements[type];
            if(validation !== undefined) {            
             var re = new RegExp(validation.reg);                
             if (validation){                   
                 if (!re.test($(field).val())){ 
                    errorCount++;                       
                    handleError($(field), validation.error);                    
                }
             }
         }
        })


    var radioList = $('input:radio');
    var radioNameList = new Array();
    var radioUniqueNameList = new Array();
    var notCompleted = 0;
    for(var i=0; i< radioList.length; i++){
      radioNameList.push(radioList[i].name);
    }
    radioUniqueNameList = jQuery.unique( radioNameList );
    console.log(radioUniqueNameList);
    for(var i=0; i< radioUniqueNameList.length; i++){
        var field = $('#' + radioUniqueNameList[i]);
        var type = field.data("validation");
           var validation = Elements[type];
        if($('input[name='+type+']:checked', '#test').val() == undefined) {
            errorCount++;   
            handleError($(field), validation.error);
        }
    }

    return errorCount == 0;
    };
};

$(function(){

    $('form#test').on('submit', function (e) {
      var NoErrors =  new Validator(this).validate();
     if(NoErrors == true) {
         $.ajax({
             url: this.action,
             type: this.method,
             data: $(this).serialize(),
             success: function() {
                 // AJAX request finished, handle the results and error msg
                $('.success_msg').fadeIn().delay(3000).fadeOut();         
                $('input , textarea').val('').removeClass('error');

             }
         });

     }
        return false;
    })

Try something like this based on your form input elements:

$('input[type="text"], textarea').val('');

Credit & References : Clearing my form inputs after submission

javascript, Try something like this based on your form input elements: $('input[type="text"], textarea').val('');. Credit & References : Clearing my form inputs  Function works great — with one oddity. After clearing the form, if I fill the form out again and click on the Submit button, the form’s value for $_POST[‘type’] is cleared also. How to retain that setting? I set it originally like this: …etc. When config.php gets invoked normally (no form reset), $_POST[‘type’] = “commit_changes”

Edit: Judging by your edited question, providing visuals, and looking at your code, you could have targeted your button(s) by mistake. In your code, you are resetting every input element. Some CSS frameworks use the <input> element with a certain type, and or, class to create the button.


An easy way to clear input fields with jQuery is simply to set the value to an empty string. Examples:

Reset, targeting id

$("input#someField").val("");

Reset, targeting name

$("input[name=someName]").val("");

Reset, targeting class

$(".someClass").val("");

By targeting specific elements, you make sure that what you wish to be reset, becomes reset, and nothing else.

Examples with checkboxes:

Resetting checkbox, targeting id

$("#idOfCheckbox").attr('checked', false);

Resetting checkbox, targeting name

$("checkbox[name=nameOfCheckbox]").attr('checked', false);

Resetting checkbox, targeting class

$(".classOfCheckbox").attr('checked', false);

The same logic follows through with most elements.

Using JavaScript to reset or clear a form, Using an HTML 'Reset' button is an easy way to reset all form fields to their In fact, we could also use the form's reset() method to achieve the same effect, not provide the functionality of clearing all the fields, including their default values. <input> elements of type submit are rendered as buttons. When the click event occurs (typically because the user clicked the button), the user agent attempts to submit the form to the server. An <input type="submit"> element's value attribute contains a DOMString which is displayed as the button's label. Buttons do not have a true value otherwise.

You can put a class on input submit and then use

  $("input:not(.uniqueClass) , textArea")

<input type="reset">, Hi there This is my HTML form code <html> <head> <title>Form headers from server);; Clear all fields each time page is loaded with Javascript. are also there on Input Fields I want those value should be clear and web  The form targets the iframe, so I pass data to it, by entering text into the field, and hitting enter, or clicking submit… data is passed, BUT for some reason, the text field does not clear… I’ve tried doing onSubmit with a function to clear data, but that is before the data gets passed,

How to clear form data when user navigate back after submit in , These make it possible to inspect and control such input fields with JavaScript All form fields can be disabled through their disabled attribute, which also exists as A button with a type attribute of submit will, when pressed, cause the form to be A value in localStorage sticks around until it is overwritten, it is removed with​  Login Form Signup Form Checkout Form Contact Form Social Login Form Register Form Form with Icons Newsletter Stacked Form Responsive Form Popup Form Inline Form Clear Input Field Hide Number Arrows Copy Text to Clipboard Animated Search Search Button Fullscreen Search Input Field in Navbar Login Form in Navbar Custom Checkbox/Radio Custom Select Toggle Switch Check Checkbox Detect Caps Lock Trigger Button on Enter Password Validation Toggle Password Visibility Multiple Step Form Autocomplete

Forms and Form Fields :: Eloquent JavaScript, Forms: Explains the RESET type of form input. Also discusses if this input is really necessary, and shows a Defines a button on a form that will return all fields to their default values. In some cases, this will clear the fields, depending on the form file, Defines a file upload box with a browse button. The Submit Button <input type="submit"> defines a button for submitting the form data to a form-handler. The form-handler is typically a page on the server with a script for processing input data. The form-handler is specified in the form's action attribute.

<input type=”reset”> », This guide to HTML forms introduces all of the elements and attributes used We also have other tutorials that cover topics such as building a form, styling and This means multiple values can be submitted with a set of For example, readonly could be applied to a submit input type and removed when a  Submit Important Attributes autocomplete. Form fields collecting certain types of user-specific information need appropriate autocomplete attributes to identify input purpose. . Users can benefit when common field types (name, address, birthdate, etc.) are represented consistently across the w

Comments
  • $("input#someField").val(""); $("input[name=someName]").val(""); $(".someClass").val("");. Basically you just set the value as empty.
  • @Martin yeah in my form fields are being cleared but submit is also clearing.see in images
  • You can put a class on input submit and then use $("input:not(.uniqueClass) , textArea")
  • @Husna can you provide the html as well? I am curious as to how your button look like, because you're most likely targeting it somehow. Is your button somehow a modified <input> element by any chance? I am asking, because some CSS frameworks use input fields with a specific type, and or, class to make it a certain button, so maybe that could be why. In your code, you are targeting ALL input elements for instance.
  • $('input[type=text], input[type=number], input[type=email], textarea').val('').removeClass('error'); i tried this its working fine.but here i have to add all input fields .Is there any other way to exclude only submit?
  • Did you tried $('input[type!="submit"], textarea').val('');` :p
  • Makes more sense perhaps to use the attribute selector, than introducing a new class: input:not([type=submit])
  • @Ullas Hunka where I have to add this code. I tried after success not coming.
  • write class inside the input tag then use this code at success method or you can use resolution given by @CBroe which is also true.
  • @CBroe this works only when you have single submit on the page. In case of multiple, you do require to make it unique in the sense
  • @UllasHunka this is about excluding submit buttons from being affected; it does not matter in that regard whether you have one or three dozen on your page.