Force user to fill all fields before enabling form submit

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

    By far the easiest, would be to rely on the HTML5 validation you're already using.

    You'd have to add required to all form controls if you want to require all of them, and that can easily be done by using jQuery's :input selector and setting the property, like so

    $(':input:not(#subnewtide)').prop('required', true)
    

    We'll exclude the submit button, as that doesn't have to be required, obviously, not that it would matter in this case.

    Then we'll listen for the input event, which covers all sorts of inputs, like typing, pasting etc, and the change event as well to cover the radio button.

    Using form.checkValidity() tells us if the form is valid, and returns a boolean, so we could use it directly to set the disabled property of the submit button.

    All together it looks like this, and that's all you need, a few lines of really simple code

    $(':input:not(#subnewtide)').prop('required', true).on('input change', function() {
        $('#subnewtide').prop( 'disabled', !this.form.checkValidity() );
    });
    

    FIDDLE

    If you have to support old browsers that don't have HTML5 validation, you can use the H5F polyfill

提交回复
热议问题