-1

I am trying to creat dynamic buttons and click event. Creating dynamic button is working but when I cliked it I am getting undefined message. What is my wrong? Sorry my lang. Thx in advance. My code is below:

$(function(){
   var i = 1;

$('button').on('click',function(){
      var r= $('<input type="button" class="dinamik" value="new button '+ i +' "/>');
      $("body").append(r);
      i++;
   });
});

    $(function(){
        $(document).on('click', '.dinamik', function(){
           var valueDeger = $(this).find('.dinamik').attr('value');
           alert("Value değeri: " + valueDeger);
    });
});

Demo is here.

Osman Villi
  • 346
  • 2
  • 24
  • You have to delegate click event for `.dynamic` element. Search for one of the thousand hundreds duplicate... – A. Wolff Jan 05 '15 at 11:31
  • 1
    @Rory McCrossan: The problem was unrelated to the title, so was not a duplicate of those answers. it was simply misuse of `this`. – iCollect.it Ltd Jan 05 '15 at 11:36

4 Answers4

1

Inside the click event handler, this referes to the button itself, there is no need to use find method:

$(function(){
    $(document).on('click', '.dinamik', function(){
       var valueDeger = $(this).attr('value');
       alert("Value değeri: " + valueDeger);
    });
});

JSFiddle Demo.


Using val() method instead of attr('value') is recommended, see this Stack Overflow question.

Community
  • 1
  • 1
dashtinejad
  • 6,193
  • 4
  • 28
  • 44
1

change this:

var valueDeger = $(this).find('.dinamik').attr('value');

to this:

var valueDeger = $(this).val(); // or this.value;

The issue is $(this) refers to the clicked element which is your input[type="button"] and you are trying to find the .find('.dinamik') in it, which is not there, so that's why it is undefined.

Jai
  • 74,255
  • 12
  • 74
  • 103
1

Demo

Try this one

$(function(){
    var i = 1;
    $('button').on('click',function(){
        var r= $('<input type="button" class="dinamik" value="new button '+ i +' "/>');
        $("body").append(r);
        i++;
    });
});

$(function(){
    $(document).on('click','.dinamik', function(){
        var valueDeger = $(this).val();
        alert("Value değeri: " + valueDeger);
    });
});
0

Change from

var valueDeger = $(this).find('.dinamik').attr('value');

To

var valueDeger = $(this).val();  
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122