Reputation: 191
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.
Upvotes: 5
Views: 97
Reputation: 104
Because you are searching for a input element in the img. You need to look for that input element in parent div or in next element.
Try this
function myfn(){
var id= jQuery(this).closest('div').find('input').val();
alert(id);
}
Upvotes: 1
Reputation: 17193
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);
});
$('#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>
Upvotes: 1
Reputation: 148110
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.
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.
Html
<img src=".." onclick="myfn(this)" class="my-class">
Javacript / jQuery
$('.my-class').click(function() {
var id = jQuery(this).next('input').val();
alert(id);
})
Upvotes: 3