views:

50

answers:

5

Hi. I am trying to add an error class to an input textbox to show a user that their input is invalid.
In the change event I am getting a reference to, what I presume is the input field and storing it in a variable.
Calling addClass on the variable does not work as expected. I have firebugged the code and $textBox is the correct textbox so I am not sure what I am missing here. I have many inputs that have the class "edit-budget-local" so I need to target the changed textbox. Thanks.

  $("input.edit-budget-local").change(function () {

    var $textBox = this;

    var newValue = $textBox.value;

    if (newValue.match(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/) == null) {

        $textBox.addClass("error");
    }


});
+2  A: 

Try

$textBox = $(this);

although there seems to be a bug (in terms of using jQuery) at ln 5 where newValue should be $textBox.val();

Ain
It's not a bug, it's just an implementation detail (perhaps not one you agree with though).
R0MANARMY
@R0MANARMY yes, agreed, but in traditional implementation it would return a TypeError: Result of expression 'newValue' [undefined] is not an object
Ain
Except that there are no types (really) in JS. and doing something like `myObject.nonExistenValue = "foo"` creates that value and sets it's value to `"foo"`. Better to think of JS objects as associative arrays than as classes.
R0MANARMY
A: 

You need to change this line: var $textBox = $(this); so that you have actually cached a copy of a jQuery object, not just the input.

g.d.d.c
A: 

The "this" that is returned is not a jQuery object. Try replacing the line

  var $textBox = this;

with

  var $textBox = $(this);
SimpleCoder
That won't work because it'll case $textBox.value call to fail since value is a not exposed (like that) by the jQuery object.
R0MANARMY
It would work, but since 'value' isn't a member of any jQuery object, two changes would need to be made; mine and the use of the val() function instead of the nonexistent 'value' property.
SimpleCoder
+1  A: 

you have error here, $textBox.addClass("error");

try like this, $("textBox").addClass("error");

mehul9595
+1  A: 

This should work if your selector and regex is correct

$("input.edit-budget-local").change(function () { 
    var textBox = $(this); 
    var newValue = textBox.val(); 

    if (newValue.match(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/) == null) { 
        textBox.addClass("error");
    } 
});
Phliplip