jQuery: Button cause validation

前端 未结 3 1906
半阙折子戏
半阙折子戏 2021-01-25 17:15

In my form I have a normal submit button which validate my form with, for example, I have

$(\"#formTest\").submit(function (e) {
        alert(\'test\');
});

&l         


        
3条回答
  •  再見小時候
    2021-01-25 17:52

    Basically this has nothing to do with validation. This is just pure form submission. To prevent your form brom being submitted on your Test button click, you should attach a click event handler to it and cancel event's propagation.

    $("button").click(function(evt){
        evt.preventDefault();
        return false;
    });
    

    Why does this happen anyway?

    The thing is that when you click your Test button, your form gets submitted because default button type (when not provided as in your case) will be submit. Check W3C Specification.

    This simply means that by providing a type="button" would change this submission behaviour as well. But this depends on the problem at hand (which is clearly not the one presented in the simplified example).

提交回复
热议问题