1

I need to use a jquery function to add a css class I have created to textboxes on a form. This class will change the border of the textbox to red, to indicate that there is an error in the textbox and that the user cannot submit until the error is fixed. Here is my current code:

function validateRequired() {
    var obj = $('.validate');
    var message = ""; 
    if (obj == null) {
        return message;
    }
    obj.each(function (index, elem) {
        if (elem.value == "") {
            message += splitCamelCase(elem.id);
            elem.attr("class", "error");
        }
    });

    return message;
}

For whatever reason, though I've used this in other points in the code to check and set attributes, I keep getting an error saying:

The property or method (elem.attr("class", "error");) is unsupported.

How can I set the border of the textbox to red using jquery?

5
  • 3
    use .addClass insted of .attr. elem.addClass('error') Commented Jul 24, 2013 at 21:43
  • I've tried that as well, and it still blows up. I'll try it again, though, because I could have very well had a typo. EDIT: I did in fact try running it with .addClass again, and it gives the same error as .attr. Thanks for the input, though! Commented Jul 24, 2013 at 21:45
  • 1
    elem is the raw HTMLElement. You need to wrap it in $(elem), or do elem.className = 'error'. Commented Jul 24, 2013 at 21:45
  • @kalley Why don't you make an aswer with that comment :) It is the good answer anyway. Commented Jul 24, 2013 at 21:46
  • FYI: HTML5 allows you to specify a custom validity checking function, and also defines the ':invalid' psuedo-class CSS selector which you can use for styling. setCustomValidity() , :invalid Commented Jul 24, 2013 at 21:55

2 Answers 2

3

elem is the raw HTMLElement. You need to wrap it in $(elem), or do elem.className = 'error'

Sign up to request clarification or add additional context in comments.

Comments

0

You could try to do instead of attribute:

    //...
    message += splitCamelCase(elem.id);
    $('this').addClass("error");

    //...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.