Force user to fill all fields before enabling form submit

前端 未结 12 2034
忘掉有多难
忘掉有多难 2021-02-07 00:49

I have a form containing various fields.

See jsFiddle demo.

My aim is to enable the submit button only when the user has filled in all fields.

So far,

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 01:29

    Use this code below. On each input, it will check all the form fields by using this function validate().

    jQuery("input[type='text'], textarea").on("input", function () {
        var isValid = validate();
        if (isValid) {
          jQuery("#subnewtide").removeAttr("disabled");
        } else {
            jQuery("#subnewtide").attr("disabled", "disabled");
        }
    });
    
    
    function validate() {
      var isValid = true;
      $('input, textarea').each(function() {
        if ($(this).val() === '')
            isValid = false;
      });
      return isValid;
    }
    

    Fiddle

    Update

    To make it validate if the form has id="new_tide" and fix about the radio button.

    $("input[type='text'], textarea").on("change input", function() {
      validate($(this));
    });
    
    $("input:radio[name='category']").on("change", function() {
        validate($(this));
    });
    
    function validate(self) {
      if (self.parents("form:first").attr("id") == "new_tide") {
        var isValid = true;
        $('input[type="text"], textarea').each(function() {
          if ($(this).val() === '')
            isValid = false;
        });
    
        if (!$("input:radio[name='category']").is(':checked'))
          isValid = false;
    
        if (isValid) {
          $("#subnewtide").removeAttr("disabled");
        } else {
          $("#subnewtide").attr("disabled", "disabled");
        }
      }
    }
    

    Fiddle

提交回复
热议问题