Reputation: 99
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
Upvotes: 0
Views: 526
Reputation: 4322
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>');
}
Upvotes: 2