1

I'm creating a page that requires a user to be able to create input elements, and I need to be able to retrieve the data from those elements based on events tied to them. I am appending them to the body of the document, and they are appending properly, but then their events aren't firing.

JSFiddle: http://jsfiddle.net/g7Sdm/2/

Base HTML:

<input type="radio" class="userInput" value="I'm a radio button that already existed when the page loaded." />Pre-Existing Radio Button
<input type="text" class="userInput userTextInput" value="Text" />
<button type="button" id="addRadio">Add Radio Button</button>
<button type="button" id="addText">Add Text Input</button>

Javascript:

$(document).ready(function() {
    $("#addRadio").click(function() {
           $("html").append("<input type=\"radio\" class=\"userInput\" value=\"I'm a dynamically added radio button!\" />New Radio Button<br />");
    });
    $("#addText").click(function() {
           $("html").append("<input type=\"text\" class=\"userInput userTextInput\" value=\"Text\" /><br />");

    });
    $(".userInput").click(function() {
        alert($(this).val()); 
    });
    $(".userTextInput").keyup(function() {
        alert($(this).val()); 
    });
});

Thanks for any help!! It is very late and I need sleep, but I'll check back in the morning.

Mr. Lavalamp
  • 1,860
  • 4
  • 17
  • 29
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Bergi Apr 21 '16 at 12:29

2 Answers2

3

You have to use the on() method, as the elements have to be binded dinamically

$(document).ready(function() {
    $("#addRadio").click(function() {
           $("html").append("<input type=\"radio\" class=\"userInput\" value=\"I'm a dynamically added radio button!\" />New Radio Button<br />");
    });
    $("#addText").click(function() {
           $("html").append("<input type=\"text\" class=\"userInput userTextInput\" value=\"Text\" /><br />");

    });
    $(document).on("click","userInput",function() {
        alert($(this).val()); 
    });
    $(document).on("click",".userTextInput",function() {    
        alert($(this).val()); 
    });
});

Here is the demo

isJustMe
  • 5,452
  • 2
  • 31
  • 47
2

Change to:

$(document).on("click", ".userInput", function() {
    alert($(this).val()); 
});

$(document).on("click", ".userTextInput", function() {
    alert($(this).val()); 
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157