This code is giving me undefined value when I try to show the value through alert message.
<div>
<input type="checkbox">
<div >
<input type="text" name="aid" id="aid" value="sample_value">
</div>
</div>
And this is what I put inside my script code..
<script src="https://code.jquery.com/jquery-3.6.0.min.js" ></script>
<script>
$('input[type="checkbox"]').click(function(){
var aid = $(this).closest("div.aid_closest").find("input[name='aid']").val();
if($(this).is(":checked")){
alert(aid);
}
});
</script>
I'd appreciate all the help and suggestion you will give to me.
CodePudding user response:
you can use next
jQuery function.
<script src="https://code.jquery.com/jquery-3.6.0.min.js" ></script>
<script>
$('input[type="checkbox"]').click(function(){
var aid = $(this).next('.aid_closest').find("input[name='aid']").val();
if($(this).is(":checked")){
alert(aid);
}
});
</script>
CodePudding user response:
.closest()
testing the element itself and traversing up through its ancestors in the DOM tree
In you example you can change
var aid = $(this).closest("div.aid_closest").find("input[name='aid']").val();
to
var aid = $(this).closest("div").find("input[name='aid']").val();