Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

$('#sum').keydown(function(){
           updateResultPrice(); 
        });

        function updateResultPrice() {
            ajax('/payment/summ', 'price='+$(this).val());
        }

Not working! Console log print: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

Upvotes: 1

Views: 23749

Answers (2)

LeoV117
LeoV117

Reputation: 124

I tested your code, as is, and didn't actually get the "Uncaught TypeError: Cannot read property 'toLowerCase' of undefined" error through the console. However, I did manage to trigger an error with the ajax() method.

The reason your code wasn't working, was down to the fact of $(this) would equal the window, and not the #sum element. six fingered man did explain this in his answer.

Try using this code instead.

// Switch 'keydown' to 'on' and include 'keyup' event to get the actual data;
// The 'on' method allows you to "string" events together. 'keyup keydown click focus...' etc.
$('#sum').on('keyup', function(){
    // Define a variable to make calling 'this' easier to write;
    var me = $(this);
    // Get the value of "me";
    var val = me.val();

    // Relay the value to the function;
    updateResultPrice( val );
});

// The function, updateResultPrice, accepts an argument of "value";
function updateResultPrice( value ) {
    // Your prior code used $(this).val() within the function;
    // The function doesn't have a $(this) to retreive the value from it,
    // So, use the "value" argument;
    $.ajax('/payment/summ', 'price=' + value); // Call "$.ajax", not "ajax";
    // The above snippet will trigger a 404, should the file not exist.

    // Just to test that it works, log it to the console;
    console.log( 'the price is: '+value );
}

For your testing pleasures, here's a JSFiddle demo of the above code.

Upvotes: 0

six fingered man
six fingered man

Reputation: 2500

You don't have a call to .toLowerCase(), but I'm guessing you're chaining it to the end of .val().

The trouble is that your this value is window, and not the #sum element.

Change your handler to this:

$('#sum').keydown(updateResultPrice); // <-- pass the function directly

function updateResultPrice() {
    ajax('/payment/summ', 'price='+$(this).val().toLowerCase());
}

Now when the handler is invoked, this will reference the #sum variable and .val() will not returnundefined.

Upvotes: 5

Related Questions