How to prevent form from being submitted?

后端 未结 10 2338
挽巷
挽巷 2020-11-21 07:06

I have a form that has a submit button in it somewhere.

However, I would like to somehow \'catch\' the submit event and prevent it from occurring.

Is there s

10条回答
  •  温柔的废话
    2020-11-21 07:27

    To follow unobtrusive JavaScript programming conventions, and depending on how quickly the DOM will load, it may be a good idea to use the following:

    Then wire up events using the onload or DOM ready if you're using a library.

    $(function() {
        var $form = $('#my-form');
        $form.removeAttr('onsubmit');
        $form.submit(function(ev) {
            // quick validation example...
            $form.children('input[type="text"]').each(function(){
                if($(this).val().length == 0) {
                    alert('You are missing a field');
                    ev.preventDefault();
                }
            });
        });
    });
    label {
        display: block;
    }
    
    #my-form > input[type="text"] {
        background: cyan;
    }
    
    

    Also, I would always use the action attribute as some people may have some plugin like NoScript running which would then break the validation. If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation. If you're using something like window.location, on the other hand, things will be bad.

提交回复
热议问题