I'm trying to create a simple inline edit for a div box. When i dblclick on the div, i wrapInner with textarea tag. That makes it editable. But how can i unwrap the textarea tag when i click outsite the textarea field. Below is what i have which is not working. Also Should i use focusout, mouseout, mouseleave or any of them.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<div id="test" style="width:300px; height:200px;">
testing
</div>
<script type="text/javascript">
$("#test").live({
dblclick: function() {
$("#test").wrapInner("<textarea/>")
},
mouseleave: function() {
$("#test > textarea").unwrap()
}
});
</script>
The unwrap() method is an inbuilt method in jQuery which is used to remove the parent element from the selected element. Syntax: $(selector).unwrap()
Answer: Use the jQuery unwrap() method With jQuery unwrap() method you can easily remove the wrapper element and keep the inner HTML or text content intact.
unwrap() method removes the element's parent and returns the unwrapped content. This is effectively the inverse of the . wrap() method. The matched elements (and their siblings, if any) replace their parents within the DOM structure.
$("#test > textarea").unwrap() is unwrapping the textarea, therefore removing the div #test, rather than removing the textarea. Instead you want:
$("#test > textarea").contents().unwrap()
As you can see from this demo, the mouseleave will trigger immediately on any mouse movement after the wrapInner, so you probably want to bind the mouseleave to the textarea inside the doubleclick handler.
A few things you should probably do differently.
$("#test").dblclick( function() {
$(this).wrapInner("<textarea/>").find('textarea').focus();
}).delegate('textarea','blur',function() {
$(this).parent().text( this.value );
});
dblclick directly to #test
dblclick handler .find() the new textarea, and .focus() on it.delegate() handler on #test instead of using .live()
blur instead of mouseleave
blur handler, set the .text() of #test to the value of the textarea. (This is important in order to pick up the edits that were made.)Example: http://jsfiddle.net/drQkp/1/
Example: http://jsfiddle.net/drQkp/2/
Here's an example that allows HTML to be typed into the textarea.
$("#test").dblclick(function() {
$(this).html($("<textarea/>",{html:this.innerHTML})).find('textarea').focus();
}).delegate('textarea', 'blur', function() {
$(this).parent().html(this.value);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With