0

Sorry about the ambiguous title but I couldn't think of anything better.

I've been struggling with this issue for a few days and haven't been able to find a way around it. A little background about my code: I have a textbox savedInfo and it stores values from different sessions. So if savedInfo is empty, I'd like to confront the user with another textbox. Once the user inputs info into the textbox and presses enter then the .val() of the textbox goes to savedInfo and the textbox is replaced with a label that has 2 buttons that appear when hovered. These two buttons give the user the ability to remove or save the textbox.

The problem I am having is that my code doesn't seem to flow correctly. For instance, I have an if statement that checks if savedInfo is empty and if it isn't then show the label text of savedInfo. Then INSIDE the keypress function I check if one of the hover buttons is pressed but the code doesn't work since it is inside the keypress function. If I take it out of the keypress function then it doesn't work for when the keypress label appears.

Probably best if I explain with pseudo code:

$(document).ready(function() {
if($("savedInfo").val() != "") {
  someDiv..innerHTML(<label>$("savedInfo").val() + hover shows buttons</label>);
} else {
   //Create textbox id `textbox`
}

$(function() {
    $("#textbox").keypress(function(e) {
        if (e.keyCode == 13) {
        //set innerHTML to a label with text of `textbox`. 
        //Check if button#1 is pressed. If yes, then do something

        //Check if button#2 is pressed. If yes, then do something
        }
    });
 });
});

So the button#1 and button#2 ids are being created inside the if but don't work inside the if because they are inside the keypress.

I hope this wasn't too confusing. Any ideas on how to make this work better? Thanks

4
  • So basically you want to generate keypress event of dynamically generated button... correct? Commented Mar 20, 2015 at 4:28
  • @MokshShah Yeah I suppose that would be a better way of putting it. Commented Mar 20, 2015 at 4:32
  • 1
    If elements are being dynamically created, you cannot bind to them since they haven't been created and attached to the DOM yet. What you want to do then is use jQuery's .on() on parent element that does exist and provide a selector. For example, $(PARENT_ELEMENT).on(EVENT, CREATED_ELEMENT_SELECTOR, CALLBACK) Commented Mar 20, 2015 at 4:35
  • 1
    if somthing is dynamically generated, $(function() { or $(document).ready(function() { wont work.... you can use $(document).on("keyup", "#your_id", function(){ // code here }); Commented Mar 20, 2015 at 4:36

1 Answer 1

2

Here's a working example with jQuery based off of your requirements.

I really don't understand what the use case is here though and it begs a few questions about reuse of the original text-box, whether this is going to occur multiple times on a page or not, why you wouldn't just show the buttons right away (vs assuming the user knows that they must press enter), and whether this could be better solved using templates? Seems that this is more difficult than it should be for such a simple interaction.

Anyhow, I hope this helps move you forward.

(function () {

    function promptForInfo(elem) {
        
        var html = "<div id='newInfoContainer'><label>New info: <input id='newInfo' type='text' placeholder='Please provide info...' /></label></div>";
        $(elem).parent().append(html);  
        
        $("#newInfo")
            .focus()
            .on("keydown", function (e) {
                
                if (e.keyCode === 13) {
                    
                    $(elem).val(this.value);
                    $(this).parent().remove();
                    
                    var buttonsHtml = "<div id='buttonContainer'><input class='saveButton' type='button' value='Save' /><input class='removeButton' type='button' value='Remove' /></div>";
                    $(elem).parent().append(buttonsHtml);
                    $(".saveButton").on("click", function (e) { saveInfo(e); });
                    $(".removeButton").on("click", function (e) { removeInfo(e); });
                    
                }            
        });
    }

    function saveInfo(e) {
        $(e.target.parentElement).remove();
        $("body").append("<p>Saved</p>");
    }
    
    function removeInfo(e) {
        $(e.target.parentElement).remove();
        $("#savedInfo").val("");
        $("body").append("<p>Removed</p>");
    }
    
    function inspectSavedInfo() {
        if (!$("#savedInfo").val()) {
            promptForInfo($("#savedInfo"));
        }
    }
    
    $(document).ready(function () {
        
        // Inspect on any change after init
        $("#savedInfo").on("change", function () { inspectSavedInfo(); });
        
        // Trigger Inspection of savedInfo on init 
        inspectSavedInfo(); 
    });

}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="savedInfoContainer">
    <label>Saved Info: <input id="savedInfo" type="text" value="" /></label>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.