1

Does anyone know now can I get the element object by using JQuery?

For Example: I have the following code to pass in the element object into the function

HTML:

<table> <tr> <td> <input type='text' ID='test' onchange='test(this)' /> <input type='text' ID='test_1' onchange='test(this)' /> <input type='text' ID='test_2' onchange='test(this)' /> <input type='text' ID='test_3' onchange='test(this)' /> </td> </tr> </table> 

JavaScript:

function test(obj) { var parent = $($($(obj).parent()).parent()).parent(); } 

Instead of passing the object over from html ( onchange='test(this)' ), any way I can capture the object by using jquery within the function by using the input ID?

3
  • .parent() returns a jQuery object. There is no need to keep wrapping it in $() Commented Aug 27, 2013 at 23:17
  • Are you trying to capture the table as an object? The <tr>, <td>? Commented Aug 27, 2013 at 23:19
  • What do you want to select? Are you talking abou the table? In that case you do $(obj).parent().parent().parent(). Please specify what you want to select. Commented Aug 27, 2013 at 23:21

4 Answers 4

1

EDITED AND UPDATED

Ah, I think I understand you now....

HTML

<table> <tr> <td> <input type='text' ID='test' /> </td> </tr> </table> 

jQuery

$(function() { var obj; $('#test').on('change',function() { obj = this; // from this point on, obj is your INPUT var v = this.val(); // v is now the value of the INPUT (what was typed) obj = this.closest('table'); // obj is now the TABLE obj = this.closest('tr'); // obj is now the ROW }); }); 
Sign up to request clarification or add additional context in comments.

Comments

1

As long as you script executes after the element exists (for example: onload or at the end of your body), you can remove the onchange attribute entirely from your HTML and do:

$('#test').change(function(){ // `this` refers to the input element var parent = $(this).parents().eq(2); //.parents needs backets }); 

2 Comments

$(this).parents().eq(0) or .eq(2) .... i can't remember which way it stacks the parents but this a better way instead of calling the parent function 3 times.
@ShanRobertson I agree that is nicer. I'm not sure which would be more efficient, but it's definitely more concise. I've updated accordingly
0

You can pass the "id" property to get the javascript/DOM element like so:

function test(obj) { var parent = $(obj).parent().parent().parent()[0]; //do something here } 

1 Comment

The table doesn't have an id, and if it did that would be the same as var parent = $(obj).parent().parent().parent()[0];
0

Instead of using onchange attribute to add the event handler, use jQuery to register it using .change()

$('table').on('change', 'input[type="text"]' function(){ //here this points to the text element var $tr = $(this).closest('tr') }) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.