0

I would like to pass the name of the element i am playing with and then change its class. I call these functions from another function.

   function addErrClass(field){
        field.removeClass("valid");
        field + Info.removeClass("valid");
        field.addClass("error")
        field + Info.addClass("error");
    }
    function addValClass(field){
        field.removeClass("error");
        field + Info.removeClass("error");
        field.addClass("valid")
        field + Info.addClass("valid");
    }

I call these functions by

if(data == "yes")
          {
            addErrClass('name');
            nameInfo.text("Please choose another usename, " + checkuser + " is in use");                
          } else {
             addValClass('name');
             nameInfo.text("Awesome, " + checkuser + " is available");  
          }

each of the elements have been given a variable name:

var name = $("#nuser");     var nameInfo
   = $("#nuserInfo");   var email = $("#email");    var emailInfo =
   $("#emailInfo");

error received:

Uncaught TypeError: Object name has no method 'removeClass'

essentially im trying to achieve the following with each function

name.addClass or email.removeClass

I will be using this on lots of fields, but thought id try and keep the code to a minimum for my problem.

EDITED WITH ANSWER. THANKS

if(data === "yes")
{
    addErrClass(name);
    addErrClass(nameInfo);
    nameInfo.text("Please choose another usename, " + checkuser + " is in use");                
 } else {
     addValClass(name);
     addValClass(nameInfo);
     nameInfo.text("Awesome, " + checkuser + " is available");  
 }

2 Answers 2

1

You are passing 'name' which is a string into the function. Since the String type does not have a method called 'removeClass' you are receiving this error. This method only exists on jQuery objects.

Since you said you had already instantiated a variable called name that is a jQuery object, try this:

if(data === "yes")
{
    addErrClass(name);
    nameInfo.text("Please choose another usename, " + checkuser + " is in use");                
 } else {
     addValClass(name);
     nameInfo.text("Awesome, " + checkuser + " is available");  
 }
Sign up to request clarification or add additional context in comments.

Comments

1

You seem to be passing the string 'name' to your function instead of the variable name which contains your jquery object. There's no removeClass method on the string object.

1 Comment

is this not the correct way. i assumed javascript would say, ok name is an object i can .addClass to it. thats why i have field + Info.addClass() also...i guess this not the correct practice

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.