-1

I have a simple form that has a button which has the task of creating an input box and button. When the generated button is clicked it should fire an event, to get the value for the generated text box. For some reason, when the button is clicked, jquery doesn't pick up on it, below is my code. Thanks.

<button id="btnclick" type="button" value="click">Click</button>

<script>
    $('#btnsend').on('click', function(){
        alert("hi");        
    });

    $('#btnclick').on('click', function(){
        $('#klappt').append('<span>Please enter the test email</span>');
        $('#klappt').append('<input id="inputemail" type="input"></input>');
        $('#klappt').append('<button id="btnsend" type="button">Send</button>')
        $('#btnclick').remove();    
    });
</script>
Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
jpavlov
  • 2,215
  • 9
  • 43
  • 58

1 Answers1

2

update your code with:

Html

<button id="btnclick" type="button" value="click">Click</button>
<div id="klappt"></div>

Jquery

         //bind click event on send (dynamic added button) button
         $('#klappt').on('click','#btnsend', function(){
                 alert("hi");        
         });


$('#btnclick').on('click', function(){
        $('#klappt').append('<span>Please enter the test email</span>');
        $('#klappt').append('<input id="inputemail" type="input"></input>');
        $('#klappt').append('<button id="btnsend" type="button">Send</button>')

        //remove button
        $('#btnclick').remove();   



    });

Check the demo on fiddle: http://jsfiddle.net/abdulrauf6182012/MjU96/

Abdul Rauf
  • 375
  • 1
  • 13
  • @jpavlov, this is a good answer. It uses event delegation to handle dynamically created elements. This is a very important concept to understand; a lot of people get hung up on this at first. Research event bubbling. – Josh Beam May 11 '14 at 14:19
  • Thanks Josh, I will read into this. – jpavlov May 11 '14 at 21:57