views:

65

answers:

2

Here is a plug-in that binds a click event on an element, which generates a container with a <textarea> and then i bind a keypress event on this new <textarea>, all is ok, but inside the keypress handler i can only get the state of text().length from when the initial click happened.

How do i get the onKeyPress function to get the state of the <textarea> at the time the keypress happened?

$.fn.pluginTemp = function(options){
    var defaults = {
            editContainer:"<div class='editContainer'><textarea></textarea></div>",
            maxChar:20,
            onKeyPress:function(){
                    console.log($(".editContainer>textarea").text())
               }

     }
    var options = $.extend(defaults,options); 
    return this.each(function(i,e){
        var el = $(e), initText
        el.bind("click", function(){
            initText = el.text();
            el.parent().append(options.editContainer);
            el.parent().find(".editContainer>textarea").html(initText);
              // isn't this function remembering the state for when its is defined?  which is on keypress?          
               return function(){
                el.parent().find(".editContainer>textarea").bind("keypress",options.onKeyPress)
            }()

        })
    })
}
+1  A: 

You could try:

return this.each(function(i,e){
            var el = $(e), initText
            el.live('click', function() {
                initText = el.text();
                el.parent().append(options.editContainer);
                el.parent().find(".editContainer>textarea").html(initText);
                  // isn't this function remembering the state for when its is defined?  which is on keypress?          
                   return function(){
                    el.parent().find(".editContainer>textarea").bind("keypress",options.onKeyPress)
                }()

            })
        })

Haven't tested as yet sorry

timothyclifford
@timothyclifford, please see my answer, thanks anyway.
adardesign
A: 

I got the problem,

Instead of getting the current value via the .html() method, I used .val()

Here is why: The .html() method when used on a <textarea> looks only at the initial state of the textarea, When you have .val() it samples the most current value.

adardesign
If you'd used .live() you'd get the same result because the function is executed at the time the event is triggered. So in other words, having it on the keypress event would have generated the html at that time. But hey, .val() works too and is much simpler :)
timothyclifford
correct, Thx much
adardesign