Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass $(this) as a parameter to another function in jQuery?

is there a way to pass $(this) to another function in jQuery?

This is what I've got but it won't work:

$(function() {

  $('[id$=price]').change(function() {
    var price = $(this).val();
    var quantity = $(this).closest('.fields').find('[id$=quantity]').val();     
    recalculate_subtotal($(this));
  });

  $('[id$=quantity]').change(function() {
    var quantity = $(this).val();
    var price = $(this).closest('.fields').find('[id$=price]').val();           
    recalculate_subtotal($(this));      
  });

  function recalculate_subtotal(element) {
    $(element).closest('.fields').find('#Subtotal').val(price * quantity);      
  }

});

(The last function is the one I want to get $(this) into.)

Thanks for any help and apologies. I am new to jQuery!

like image 986
Tintin81 Avatar asked Nov 30 '22 14:11

Tintin81


1 Answers

That will work fine, although one theing to note is that if you're passing the jQuery object ($(this)) you dont need to wrap it again in $():

$('[id$=price]').change(function() {
    var price = $(this).val();
    var quantity = $(this).closest('.fields').find('[id$=quantity]').val();     
    recalculate_subtotal($(this));
})


function recalculate_subtotal($element) {
    $element.closest('.fields').find('#Subtotal').val(price * quantity);      
}
like image 116
Jamiec Avatar answered Dec 10 '22 23:12

Jamiec