Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a reference of DOM object to jQuery function?

I want to pass a reference of the DOM object to a jQuery function. However the function does not get a reference to the DOM object. It does get a string containing the DOM object. So i get an error on the following example

<input type="text" size="30" onchange="change_total_price(this)" id="priceField">

.

function change_total_price(input) {
    input.closest('div').find('#amountField').val());
}
like image 867
Flexo Avatar asked Dec 16 '22 23:12

Flexo


1 Answers

You need to wrap it, like this:

function change_total_price(input) {
  var val = $(input).closest('div').find('#amountField').val();
}

this, being input in the function is a DOM element, but .closest() is a jQuery object method so you need to wrap it in $() to get a jQuery object if you want to use it.

Alternatively do this outside of your markup, like this:

$(function() {
  $("#priceField").change(function() {
    var val = $(this).closest('div').find('#amountField').val();
  });
});

This way binds the change event handler to the id="preiceField" element, you can remove the in-line onchange="change_total_price(this)"...it's both cleaner and easier to maintain (can be outside your page in an external .js loaded and cached once, for example).

As an aside, IDs should be unique, so it doesn't need to be relative at all, both of the above examples can just be:

var val = $('#amountField').val();
like image 173
Nick Craver Avatar answered Dec 28 '22 00:12

Nick Craver