开发者

disable submit only if valid

开发者 https://www.devze.com 2023-02-14 04:01 出处:网络
im using jquery with asp.net mvc. Im doing something like this so that the submit button becomes d开发者_Python百科isabled when clicked.

im using jquery with asp.net mvc. Im doing something like this so that the submit button becomes d开发者_Python百科isabled when clicked.

but if there are validation errors i dont want it to be disabled.

 $('form').submit(function () {
        if ($('form').valid()) {
            $('input[type=submit]', this).attr('disabled', 'disabled');
        }
    });

this makes it disabled, but even if there are validation errors. whats wrong?


EDIT: i'll try again after my first screw up :P

$('form').submit(function () {
        if ($('form').valid()) {
            $('input[type=submit]', this).attr('disabled', 'disabled');
        }
    });

Maybe there are other forms on the page, and it's validating the wrong one?

$('form').submit(function () {
        if ($(this).valid()) {
            $(this).find('input[type=submit]').attr('disabled', 'disabled');
        }
    });

oh and did you $('form').validate() to enable validation (which I would guess is called automatically by MVC if you're using MVC's validation, but I'm not 100% sure about that)?


$('form').valid() returns an error when I run it in the console. Are you even sure that's a valid function? AFAIK it is not.

In CSS, the :valid pseudo-class is applied to specific inputs, not the form element. I can only assume that it's the same deal in JavaScript.

With that said, HTML validation has spotty browser support at this time and you shouldn't blindly rely on it. If your form is as simple as a few "required" fields, you could loop through each input element and check if this.getAttribute('required') && this.value != ''.


Another trick (not specifically relevant but i had a similar problem) is that if you have any server side validation, or anything really happening on the server.

In the code behind, first thing your function should do is RE-ENABLE THAT BUTTON. Because i had a weird bug (still can't figure out how they did it) but basically: client side validation was fine (also if they have JS disabled), and in the server i caught an error, i displayed that error in a non-obtrusive way in the dom on post back. So they could attempt to rectify whatever the hell went wrong. But obviously the button was disabled... so i got millions of complaints. Therefore, moral of the story, Re-enable the button so that if it posts back to the same page your button will still work. Yay.


Did you use another jquery plugin to use a "valid()" function on your form? Because $('form').valid() doesn't mean anything in Javascript with the core jquery lib

0

精彩评论

暂无评论...
验证码 换一张
取 消