James James -4 years ago 36
Javascript Question

Nested functions in jQuery and (this)

sorry that this question is so basic but i cannot figure it out..

I would like to know how i can convert this javascript (jquery) into a function that can be called from the handler and utilises $(this) as I have many elements that will need to use this handler.

here is the complete jquery atm..

$(document).ready(function(){

$(document).on('keyup', '.order-item', function(){
var price = +$(this).data('price');
var hmany = +$(this).find('.quantity').val();
var item = $(this).data('name');
var subTotal = price * hmany;


$('.confirm-ul').append('<li>' + item + ' x ' + hmany + ' = €' + subTotal + '</li>');

});
});


So i want to put this (below) into a function and call it from the handler.. The problem I have had is that (this) does not work when the code is in its own function.

var price = +$(this).data('price');
var hmany = +$(this).find('.quantity').val();
var item = $(this).data('name');
var subTotal = price * hmany;


$('.confirm-ul').append('<li>' + item + ' x ' + hmany + ' = €' + subTotal + '</li>');


Thank you

Answer Source

You can do something like this:

$(document).ready(function(){
    $(document).on('keyup', '.order-item', anotherFunction);
});
function anotherFunction() {
    var price = +$(this).data('price');
    var hmany = +$(this).find('.quantity').val();
    var item = $(this).data('name');
    var subTotal = price * hmany;
    $('.confirm-ul').append('<li>' + item + ' x ' + hmany + ' = €' + subTotal + '</li>');
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download