Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  135] [ 7]  / answers: 1 / hits: 5746  / 10 Years ago, fri, april 11, 2014, 12:00:00

all. I have html layout like this:



<div class=row id=1>
/*Other code has nothing to do with <div class=form-group col-lg-1>*/

<div class=form-group col-lg-1>
<input type=button class=btn btn-default onclick=updateLine() value=Update>
</div>
</div>


I want to obtain the div's ID, in this case, which is 1.



This is what I did.



function updateLine() {
alert(this.parent().parent().attr(id));
}


However, it failed, then I check



alert(this);


it returns to me the window object.



So the question is , how could I get the id's value, which is 1.



Thanks.


More From » jquery

 Answers
2

You do not need to pass this to the function. In an event handler this is the element clicked. However, to use .parent() etc on it you need the jQuery object for that element which is $(this)



Also, I would strongly recomment using .closest instead of .parent().parent(). Something like



$(this).closest('div.row').attr('id')


Way less likely to break when you make small layout changes...



The comments about using jQuery events instead of inline javascript are also good advice.



Example:



<div class=row id=1>
/*Other code has nothing to do with <div class=form-group col-lg-1>*/

<div class=form-group col-lg-1>
<input type=button class=btn btn-default value=Update>
</div>
</div>

<script type=text/javascript>
$(function(){
function updateLine(event){
alert( $(this).closest('.row').attr('id') );
}

// If you have other buttons add a class like 'btn-update' and use that instead
$('body').on('click', '.btn-default', updateLine);

});
</script>

[#46086] Friday, April 11, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;