Muhamad Azam
Muhamad Azam

Reputation: 45

How to Pass values javascript onclick to jquery function

I have this this image with onclick function on it

<img id='1213' src='img/heart.png' onclick='heart(this.id)'>

which to call this function :

function heart(id) {
    $('#heart').dialog('open');
    return false;
}

How can i show the ID inside the div?

<div id="heart">
     Name : ABC
     ID : The ID need to be here 
</div>

P/S : i have reason why i want to use the onclick instead directly using the jquery get val from the image id directly.

Upvotes: 1

Views: 156

Answers (4)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly, you should use JavaScript to attach your events. You've already included jQuery, so we may as well use that. Once you attach the event, you can use the text() method to set the innerText property of the span within the target div. Try this:

<img id="1213" class="heart" src="img/heart.png" />

<div id="heart">
     Name : ABC
     ID : <span></span>
</div>
$('.heart').click(function() {
    $('#heart span').text(this.id).dialog('open');
});

Upvotes: 3

Adersh M
Adersh M

Reputation: 586

If you are using HTML5, you could make use of data-* attribute.

<img id="someid" src="img/heart.png" data-id="1213"/>

    $('#someid').click(function(e) {
        var id = this.getAttribute("data-id");
        $('#heart').text(id).dialog('open');
    });

Upvotes: 0

Thomas Theunen
Thomas Theunen

Reputation: 1274

You can do it like this.

function heart(id) {
  $('#heart').text(id).dialog();
  return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<img id='1213' src='img/heart.png' onclick='heart(this.id);'>


<div id="heart">

</div>

Upvotes: 0

Satpal
Satpal

Reputation: 133403

To show image id, You can use

$('#heart').html(id).dialog('open'); 

I would recommend you not to use ugly inline event handler. You can bind event using jQuery. Here I have added a CSS class to img element then we can use Class Selector $(".class") to bind event

HTML

<img class="myImage" id='1213' src='img/heart.png'>

Script

$(function() {          
    $('.myImage').on('click', function(){
        $('#heart').html(this.id).dialog('open'); 
    });
});

Upvotes: 2

Related Questions