user2780757
user2780757

Reputation: 191

Please tell me why this isn't working! (basic jquery)

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

Answers (3)

Rahul Khandelwal
Rahul Khandelwal

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

Vishal Suthar
Vishal Suthar

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);
});

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>

Upvotes: 1

Adil
Adil

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.

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

  • Close input and img tags with /
  • Enclose the attribute values in double quotes, e.g. 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);
})

Upvotes: 3

Related Questions