0

I have edited my code using event handler. But it still does not seem to work, what am I doing wrong?

    $(document).ready(function(){
    $("#hour1").on("click", function( event ){
        $("#hour1").remove();
        $("#hour1Data").append("<input id='hour1Input' type='text'/>");
    });
});

$(document).ready(function(){
    $("#hour1Input").on("click", function( event ){
        $("#hour1Input").remove();
        $("#hour1Data").append("<p id='hour1'><?php echo $hour1; ?></p>");
    });
});

Original Post:

I am making a small webapp consisting of a table of text. The user can change the text by clicking on it, the text turns in to a text box, the user can enter the new text, and press enter. Then the textbox will go back to the original p tag with the updated text.

I am trying to do this using jQuery. Below is my code.

//User clicks p tag named "#hour1". 
$(document).ready(function(){
    $("#hour1").click(function(){
        $("#hour1").remove();
        $("#hour1Data").append("<input id='hour1Input' type='text'/>");
    });
});

//After entering text, user presses enter. 
$(document).ready(function(){
    $("#hello1Input input").keypress(function (e) {
    if (e.keyCode == 13) {{
        //process text//
        $("#hour1Input").remove();
        $("#hour1Data").append("<p id='hour1'><?php echo $hour1; ?></p>");
    }
    });
});

Right now on click of "#hour1" it turns in to a text box which is good! But any ID's that are on the content being dynamically created are not being recognized by jQuery making it impossible to do anything with it. How do I make the new content so the ID's are recognized and useable by Jquery. Thanks for any help!

Ben L
  • 127
  • 1
  • 1
  • 11
  • 1
    learn [Event Delegation](http://learn.jquery.com/events/event-delegation/) – Satpal May 09 '16 at 07:31
  • The reason is because you are creating the event handlers on load, yet the inputs are being added *after* the DOM has been created. You therefore need to use a delegated event handler. See the question I marked as duplicate for more information. – Rory McCrossan May 09 '16 at 07:31
  • Also note that using a pattern of incremental id attributes is not a great idea. It becomes a pain to maintain is not very DRY at all. It's much better practice to use common classes and DOM traversal to find the required elements. – Rory McCrossan May 09 '16 at 07:32

0 Answers0