0

Jquery : 3.x, Tomcat7

Problem :

var htmlStr
for(var i=0;i<data.length;i++){           
  htmlStr += "<input  class='my_button' type='button' data-value='"      
  + data[i].value + "' value='" + data[i].value + "'/>";                
}

$("#keyvals").html(htmlStr);

$('.my_button').click(function(){
    alert(this.data-value);
});

Question : For the dynamically created 'input with same class as class='my_button' , How to get the value on clicked ?

Help is highly appreciated.

N.S.Karthik
  • 485
  • 13
  • 29

3 Answers3

0

Try:

$('.my_button').click(function(){
    alert($(this).data('value'));
});

JSFiddle: https://jsfiddle.net/NotABlueWhale/xb838mdz/

NotABlueWhale
  • 795
  • 7
  • 18
0

.data is a function, the name of the data element is the argument. It's also a jQuery function, so you need to use $(this).

$('.my_button').click(function(){
    alert($(this).data('value'));
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

A dash (-) is not valid in a JS variable, it is seen as a minus

You can do

  • alert(this.getAttribute("data-value")); // DOM
  • alert($(this).attr("data-value")); // jQuery
  • alert($(this).data("value")); // jQuery DATA

However you MAY also want/need to delegate since the button is dynamically generated

$("#keyvals").on("click",".my_button",function(){

Event binding on dynamically created elements?

var data = [{value: "ONE"}, 
            {value: "TWO"}, 
            {value: "THREE"}], 
  htmlStr="";
 
for (var i = 0; i < data.length; i++) {
  htmlStr += "<input  class='my_button' type='button' data-value='" +
    data[i].value + "' value='" + data[i].value + "'/>";
}

$("#keyvals").html(htmlStr);

// this works without delegation because it is after the insertion 
$('.my_button').click(function() {
  console.log($(this).attr("data-value"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="keyvals"></div>
Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236