Script
function myfn(){
var id= jQuery(this).find('input').val();
alert(id);
}
HTML
<div>
<img src=".." onclick="myfn()" >
<input type=hidden value=1 >
</div>
The function is proper but the id value shows undefined. I have included all the necessary apis.
You need to pass the event source using this to myfn, also you need next instead of find, as find will look in descendants and next will look siblings.
Live Demo
Javascript
function myfn(obj){
var id= jQuery(obj).next('input').val();
alert(id);
}
In html
<div>
<img src=".." onclick="myfn(this)" >
<input type="hidden" value="1" >
</div>
As a additional note
input
and img
tags with /
type
and value
.You can bind event using jQuery click instead of inline event bind you have in question. I would suggest you to use a class to bind event, for this you need to assign class to img. This will make the this and $(this) available in the handler.
Live Demo
Html
<img src=".." onclick="myfn(this)" class="my-class">
Javacript / jQuery
$('.my-class').click(function() {
var id = jQuery(this).next('input').val();
alert(id);
})
Another option would be:
HTML:
<div>
<img src="http://placehold.it/120x120&text=image1" id="myimg" />
<input type="hidden" value="1" />
</div>
JS:
$('#myimg').click(function myfn(){
var id= jQuery(this).next('input').val();
alert(id);
});
Live Demo
$('#myimg').click(function myfn() {
var id = jQuery(this).next('input').val();
alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://placehold.it/120x120&text=image1" id="myimg" />
<input type="hidden" value="1" />
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With