Use Parent with input -- jquery

Asked

Viewed 39 times

1

I am trying to recover the id of a parent div of an input

<div id="parentDiv">
    <input type="text" onfocus="mostra(this)">
</div>

Using the onFocus function, it returns me Undefined

function mostra()
{
    alert($(this).parent().attr("id"));  // output: undefined
}

However, by way of curiosity, this way works and returns me the right data

$(document).ready(function(){
  alert($("input").parent().attr("id"));  // output: parentDiv
});

What I’m doing wrong in using Parent() using onfocus?

  • The problem there is that the this there in alert($(this).parent(... is not referring to this past as function parameter showcase() in HTML, but, yes to this of the context where it is inserted, so it returns Undefined, should take the parameter this passed in the function and then do the necessary logic: function mostra(this_referenciado) { alert($(this_referenciado).parent().attr("id")); })

  • @Leandrade sorry me.. I didn’t quite understand your placement. It would be possible, please, to show in code how the solution would be?

  • Do not greet, do not thank and do not defer in the publications. See What kind of behavior is expected from users?

1 answer

3


<div id="parentDiv">
    <input type="text" onfocus="mostra(this)">
</div>

In the HTML above, you are invoking the function mostra passing a reference of the element itself as a parameter.

Therefore, in the function mostra you need to capture this parameter through the function’s arguments declaration:

function mostra(elem)
{
    alert($(elem).parent().attr("id"));
}

Pass the this as argument does not change the context of this in function, this is contextual, and has different values in different contexts.

  • 1

    Just what I needed! Thank you so much for your time and availability.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.