Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

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.

like image 730
user2780757 Avatar asked Jun 16 '15 05:06

user2780757


2 Answers

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);
})
like image 60
Adil Avatar answered Sep 28 '22 11:09

Adil


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>
like image 24
Vishal Suthar Avatar answered Sep 28 '22 13:09

Vishal Suthar