Making 'file' input element mandatory (required)

后端 未结 8 618
忘掉有多难
忘掉有多难 2020-12-31 00:11

I want to make (an HTML) \'file\' input element mandatory: something like


But it i

8条回答
  •  执念已碎
    2020-12-31 00:34

    You could create a polyfill that executes on the form submit. For example:

    /* Attach the form event when jQuery loads. */
    $(document).ready(function(e){
    
    /* Handle any form's submit event. */
        $("form").submit(function(e){
    
            e.preventDefault();                 /* Stop the form from submitting immediately. */
            var continueInvoke = true;          /* Variable used to avoid $(this) scope confusion with .each() function. */
    
            /* Loop through each form element that has the required="" attribute. */
            $("form input[required]").each(function(){
    
                /* If the element has no value. */
                if($(this).val() == ""){
                    continueInvoke = false;     /* Set the variable to false, to indicate that the form should not be submited. */
                }
    
            });
    
            /* Read the variable. Detect any items with no value. */
            if(continueInvoke == true){
                $(this).submit();               /* Submit the form. */
            }
    
        });
    
    });
    

    This script waits for the form to be submitted, then loops though each form element that has the required attribute has a value entered. If everything has a value, it submits the form.

    An example element to be checked could be:

    
    

    (You can remove the comments & minify this code when using it on your website)

提交回复
热议问题