Zeretil
Zeretil

Reputation: 297

Uncaught TypeError: Cannot call method 'toLowerCase' of undefined

Yes, I have checked the other questions regarding the same problem, but none of them match my specific problem, so I hope someone can help me out here.

So, I have a button:

<input type="button" class="operator" value="/" />

And when I click it, I get the error mentioned in the title. The function it calls:

function operators(origVal) {
                var Oper = "";
                Oper = ($(this).val());
                console.log(Oper, origVal);       
            };

origVal is just a number I pass when I call the function.

So yeah, everything works perfect when I reduce the function to

function operators(origVal) {
                var Oper = "";
                console.log(Oper,origVal);       
            };

EDIT: The part that was here was not my code and seems to cause some confusion and wasting your time trying to figure it out.

Upvotes: 0

Views: 1433

Answers (2)

adeneo
adeneo

Reputation: 318192

A function creates a new scope, so inside

function operators(origVal) {
    console.log(this); // returns the scope of the function

    // "this" is the function, or more likely the window in this case, 
    // and it has no val() method
}

FIDDLE

this is not what you think it is, and it certainly has no value property, and that is what is causing the error, see the Fiddle.

If you where to use jQuery event handlers, the scope would be set for you

$('.operator').on('click', operators);

then this inside the function would be the bound element.

EDIT:

If the function is called within the event handler, you can do

$(".operator").click(function () { 
    operators.apply(this, [CurVal]);
});

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

The syntax of apply() is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

More on MDN

Upvotes: 3

bipen
bipen

Reputation: 36531

you cannot call $(this) inside a function call .. i am sure it is a scoping issue...

for $(this) to work ,either use jquery's click event handler or pass this to the function onclick call

since you haven't showed us , how actaully are you calling the operator function.. assuming this is how you are doing it..

  ... onclick="operators(this,somevalue)"..


 function operators(this,origVal)
  {
      var Oper = "";
      Oper = ($(this).val());
      console.log(Oper, origVal); 

  }

updated

use call() or apply() to specify this context is button here and not function itself

$(".operator").click(function () {
   operators.call( this, CurVal ); 
}

Upvotes: 0

Related Questions