views:

31

answers:

1

I want to pass a reference of the DOM object to a jQuery function. However the function do not get a reference but 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());
}
+6  A: 

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();
Nick Craver