0

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 enter image description here

After submit form enter image description here

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;
    })
Husna
  • 1,286
  • 4
  • 19
  • 48
  • `$("input#someField").val("");` `$("input[name=someName]").val("");` `$(".someClass").val("");`. Basically you just set the value as empty. – Martin Jun 06 '18 at 08:49
  • @Martin yeah in my form fields are being cleared but submit is also clearing.see in images – Husna Jun 06 '18 at 08:53
  • You can put a class on input submit and then use $("input:not(.uniqueClass) , textArea") – Ullas Hunka Jun 06 '18 at 08:56
  • @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 `` 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. – Martin Jun 06 '18 at 09:00

3 Answers3

1

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.

Martin
  • 2,326
  • 1
  • 12
  • 22
0

Try something like this based on your form input elements:

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

Credit & References : Clearing my form inputs after submission

Umair Mohammad
  • 4,489
  • 2
  • 20
  • 34
  • `$('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? – Husna Jun 06 '18 at 09:11
  • Did you tried $('input[type!="submit"], textarea').val('');` :p – Umair Mohammad Jun 06 '18 at 10:07
0

You can put a class on input submit and then use

  $("input:not(.uniqueClass) , textArea")
Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
  • Makes more sense perhaps to use the attribute selector, than introducing a new class: `input:not([type=submit])` – CBroe Jun 06 '18 at 09:00
  • @Ullas Hunka where I have to add this code. I tried after success not coming. – Husna Jun 06 '18 at 09:04
  • 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. – Ullas Hunka Jun 06 '18 at 09:16
  • @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 – Ullas Hunka Jun 06 '18 at 09:18
  • @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. – CBroe Jun 06 '18 at 09:19
  • @CBroe yes, for excluding you are absolutely accurate – Ullas Hunka Jun 06 '18 at 09:23