开发者

using .change() in jQuery for validation

So I am using jQuery's .change() function to trigger validation on the other fields in that particular table. See code below.... The problem I am running into is this: If I type something in an input field, and then erase it, it still considers it changed, and requires the other fields. I can see this being a problem for the user, is there anyway around this?

p.s. class="R" is from my custom validation and makes it a required field.

$('#t1 :input').change(function(){                                          

        var $t1Input = $('#t1Table :input:not(input[type=hidden])');
        var hasData = false;


   $t1Input.each(function(){
            if($(this).val().length > 0){
   开发者_运维百科             hasDatat1 = true;
                return false;
            }
        });
        // Change class of input field to "R" if something has been changed 
            if(hasDatat1)
                $t1Input.addClass('R');                                                                  
            else
                $t1Input.removeClass('R');
        });


Try this:

$('#t1 :input').change(function(){
    if ($(this).val() == '') return;


You could use the approach outlined here to detect a "real" change: Getting value of select (dropdown) before change


You can use the .data() function of JQuery to store the value and check for real change in your code


If I read your question right, this will validate each individual input without validating all inputs in the t1Table on every change.

$('#t1 :input:not(input[type=hidden])').change( function() {
    if( $(this).val() == '' )  { $(this).addClass('R'); }
    else { $(this).removeClass('R'); }
} );

I know you didn't ask this, but you mentioned "problem for the user" so I'm reading into your question. For usability, I'm not saying switch to Dojo instead of JQuery. In fact, I end up using JQuery more than Dojo because it seems like there's a bigger following. However, Dojo has a very good way of validating form data and giving the user instant feedback without being annoying. You might want to check it out for ideas for giving the user a good UI flow.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜