0

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

James
  • 85
  • 5
  • Do you want the whole part, including `$(document).on()` in the function, or just the callback portion? Showing what you want with (psuedo-)code will be helpful. – samanime Jun 13 '17 at 20:30
  • In both of your examples, `this` is the element that the keyup was performed on. I don't see a problem. missing code? – Kevin B Jun 13 '17 at 20:31
  • Please show the code where you have a problem with `this`, because jQuery always binds `this` to whatever function you pass to `on`. – trincot Jun 13 '17 at 20:33
  • sorry no, everything apart from the $(document).on line.. that was a mistake – James Jun 13 '17 at 20:34
  • and how is the function defined? and how is it called? how a function is called impacts what `this` is. – Kevin B Jun 13 '17 at 20:36
  • possible duplicate? https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work/3127440#3127440 – Kevin B Jun 13 '17 at 20:37
  • note, document ready isn't needed. the document is always ready to have events bound to it. – Kevin B Jun 13 '17 at 20:44
  • Thanks for all the input, sorry the question was not clear. – James Jun 13 '17 at 20:53

1 Answers1

2

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>');
}
Arnold Gandarillas
  • 3,279
  • 24
  • 35