Tom
Tom

Reputation: 2634

jquery data attribute with input selector in a loop

I have an html table built from a database query which loops through and creates a button for each camera name found and puts them in a table:

<?php
for($i=0;$i<$num_rows;$i++)
{

?>
<tr>
<td>
    <input type="submit" class="play" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">
</td>
</tr>

<?php
}
?>

This resolves to something like this:

<tr>
<td>
    <input type="submit" class="play" data-hash="0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5" value="Office Window">
</td>
</tr>
<tr>
<td>
    <input type="submit" class="play" data-hash="b824cba374c3d5ab7806ad8260c939323c03147b" value="aaa">
</td>
</tr>
<tr>
<td>
    <input type="submit" class="play" data-hash="ec9658f0c1855e2e2ac09ae284f5e6990dbf445d" value="laptop">
</td>
</tr>

Notice the data hash attribute is different for each button. I want to process this button with my jquery code:

$(".play").click(function(){
    var camerahash = $('input').data('hash');
    console.log($('input').data('hash'));
});

No matter which button I click I will always get the hash from the first button I click: 0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5. Any help is appreciated.

Upvotes: 0

Views: 372

Answers (5)

Justin Taylor
Justin Taylor

Reputation: 81

You need to specify which input element to read. Try something like:

$(".play").click(function(){
    $this = $(this);
    var camerahash = $this.data('hash');
    console.log($this.data('hash'));
});

Upvotes: 3

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67219

You could always grab them by using the .attr(data-hash) html5 attribute.

Try:

$('.play').on('click', function() {
      var _hash = $(this).attr('data-hash');
      console.log(_hash);
});

Upvotes: 1

Andrew Sledge
Andrew Sledge

Reputation: 10361

Your selector will return the first one that it comes to. Use this instead

<script>
    $("input.play").click(function() {
        alert($(this).data('hash'));
    });
</script>

Upvotes: 0

Musa
Musa

Reputation: 97727

$('input').data('hash') gives you the data attribute of the first input in the selection use $(this).data('hash') to get the data attribute of the currently clicked input

Upvotes: 3

JanHocevar
JanHocevar

Reputation: 199

You are always calling the first object of .play. This would be a correct way:

$('.play').on('click', function(){

  var camerahash = $(this).data('hash');

});

Upvotes: 2

Related Questions