2014-11-28 4 views
1
$('#sum').keydown(function(){ 
      updateResultPrice(); 
     }); 

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

Не работает! Консоль печать журнала: Uncaught TypeError: Не удается прочитать свойство «toLowerCase» неопределеннойUncaught TypeError: Невозможно прочитать свойство 'toLowerCase' of undefined

+2

В коде, который вы отправили, нет вызова 'toLowerCase'. – Pointy

+0

Это потому, что ошибка возникает из кода jQuery, который применяет '.toLowerCase()' к переменной, которая, по-видимому, не определена. – Bobort

ответ

5

Вы не вызов .toLowerCase(), но я предполагаю, что вы его сцепление до конца .val().

Беда в том, что ваше значение this составляет window, а не элемент #sum.

Изменение обработчика к этому:

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

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

Теперь, когда обработчик вызывается, this будет ссылаться на переменную #sum и .val() не вернется undefined.

0

Я протестировал ваш код, как есть, и на самом деле не получил сообщение «Uncaught TypeError: Can not read property» toLowerCase «неопределенной» ошибки через консоль. Однако мне удалось вызвать ошибку с помощью метода ajax().

Причина, по которой ваш код не работал, уменьшился до $(this), равный window, а не элемент #sum. six fingered man объяснил это в своем ответе.

Попробуйте использовать этот код вместо этого.

// 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); 
} 

для тестирования удовольствий, вот JSFiddle демо выше кода.

Смежные вопросы