I’m having a hard time selecting the direct parent div of an input element in jquery, here’s what I’ve tried so far, I’ve also included the output I got from each one when I tried to press enter on the text box with the placeholder of bunso:
<script src="jq.js"></script>
<script>
$(function(){
$('#grand_lolo').keypress(function(e){
var box = $(this).parents('div').attr('id'); //undefined
var box2 = $(this).parent().closest('div').attr('id'); //undefined
var box3 = $(this).parent().attr('id'); //(an empty string)
var box4 = $(this).find("div:first").attr("id"); //lolo
var box5 = $(this).find("div").attr("id"); //lolo
var box6 = $(this).find("div:last").attr("id"); //apo
var box7 = $(this).closest('div').attr('id'); //grand_lolo
console.log(box);
console.log(box2);
console.log(box3);
console.log(box4);
console.log(box5);
console.log(box6);
console.log(box7);
});
});
</script>
<div id="grand_lolo">
<input type="text" placeholder="grand_lolo"/>
<div id="lolo">
<input type="text" placeholder="lolo"/>
<div id="mama">
<input type="text" placeholder="mama"/>
<div id="ate">
<input type="text" placeholder="ate"/>
</div><!--end of ate-->
<div id="bunso">
<input type="text" placeholder="bunso"/>
</div><!--end of bunso-->
</div><!--end of mama-->
<div id="papa">
<input type="text" placeholder="papa"/>
<div id="kuya">
<input type="text" placeholder="kuya"/>
<div id="apo">
<input type="text" placeholder="apo"/>
</div><!--end of apo-->
</div><!--end of kuya-->
</div><!--end of papa-->
</div><!--end of lolo-->
</div><!--end of grand_lolo-->
As you can see the correct output should be the id of the div directly enclosing the input element.
just attach your
keypresstoinputelements – http://jsfiddle.net/hyEhh/