0

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');
        });
Dan
  • 1,408
  • 8
  • 31
  • 52
  • You want to validate each field individually as it changes so that you can give some indication that THAT field is valid when they finish typing a valid string? correct? – Kevin Nelson May 18 '11 at 14:23
  • @Kevin, it is going to be an alert box that pops up for the validation, but all of that is already done. The .change() seems to trigger on any change, even if it is set back to its original state. i.e. textbox having information entered into it, and then the user deleting that information. – Dan May 18 '11 at 14:53

4 Answers4

1

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

Community
  • 1
  • 1
Tao
  • 12,438
  • 7
  • 61
  • 72
1

Try this:

$('#t1 :input').change(function(){
    if ($(this).val() == '') return;
Mike Thomsen
  • 33,992
  • 10
  • 50
  • 76
1

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

Grooveek
  • 9,639
  • 1
  • 25
  • 34
0

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.

Kevin Nelson
  • 7,156
  • 4
  • 29
  • 39