views:

27

answers:

3

I have some javascript code that reads:

$(this).keyup(function () {
  if(regex.test(this.value))
    this.style.backgroundColor=config.validColor;
else
    this.style.backgroundColor=config.invalidColor;
});

This is supposed to provide a visual cue to the user, about the field he or she is typing in, however, this just flips the colour on every keypress.

A: 

Your callback function for the keyup event should be take an eventObject parameter. This exposes a which property that provides information about the keycode/character code that was pressed.

You should pass that to your test to see if a keypress is valid/invalid.

casperOne
A: 

Not knowing what response the test function returns, you can try like this:

$(this).keyup(function () {
  if(!regex.test(this.value))
    this.style.backgroundColor=config.invalidColor;
else
    this.style.backgroundColor=config.validColor;        
});
Sarfraz
A: 

Yeah, it heavily depends on the regex you are matching.

You should try to debug it first:

(I will be continuing with Sarfraz's code).

$(this).keyup(function () {
  if(!regex.test(this.value))
    this.style.backgroundColor=config.invalidColor;
    $('#debug').html('invalid color');
else
    this.style.backgroundColor=config.validColor;        
    $('#debug').html('valid color!');
});

Also, since you are using jQuery, you should rely more on its 'write less' philosophy.

$(this).keyup(function () {
  if(!regex.test(this.value))
    $(this).css('backgroundColor', config.invalidColor);
    $('#debug').html('invalid color');
else
    $(this).css('backgroundColor', config.validColor);
});

Maybe you should paste the regular expression code and what you are trying to achieve.

metrobalderas