Force user to fill all fields before enabling form submit

前端 未结 12 2041
忘掉有多难
忘掉有多难 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:30

    Here is a quick way to accomplish that. It involves attaching a change event listener to :radio and :checkbox elements and an input event listener to other elements. These can both use a common predefined handler that will count the number of unfilled element each time each of these events fires on the appropriate element.

    function checkForm() {
        //define and initialize variables
        var unfilled = 0,
            form = $(this.form);
    
        //disable submit button if enabled
        $(':submit', form).prop('disabled', true);
    
        //count number of unfilled elements
        $(':input', form).each(function() {
            if( $(this).is(':radio,:checkbox') ) {
                $('input[name=' + this.name + ']:checked').length || unfilled++;
            } else {
                $('[name=' + this.name + ']').val() || unfilled++;
            }
        });
      
        //enable submit button if no unfilled element is found
        unfilled || $(':submit', form).prop('disabled', false);
    }
    
    //set up event listeners to fire above handler
    $(':text,textarea,select').on('input', checkForm);
    $(':radio,:checkbox').on('change', checkForm);
    
    
    Title:
    Description:
    Tag:
    Category: Animation

提交回复
热议问题