jQuery: Button cause validation

前端 未结 3 1903
半阙折子戏
半阙折子戏 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:46

    you will want to make a handler for the button, and put a preventDefault() on it's event.

    $('button').click(function(e){
        e.preventDefault();
        alert('i clicked!');
    });
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-25 18:02

    change <button>Test</button> into <input type="button" id="test" >Test</input>

    0 讨论(0)
提交回复
热议问题