my code is this. on jsfiddle.
var inp = $('<input>').attr({'class':'txtEdit txt',
'type':'text'})
.val($(this).html()).blur(function (){
if($(this).val().length != ''){
$(txt).replaceWith($(editable)
.html($(this).val()));
}
else{ alert("Cannot contain empty value!")}
}).keydown(function (e){
if(e.keyCode == 13 || e.keyCode == 9){
e.preventDefault();
$(this).trigger('blur');
}
}).appendTo($(txt));
I am creating an input element with lots of events and adding to div. Now i want to focus it as it is appended to DOM. but focus does not seem to be working.
Here's the total code.
<html>
<head>
<title>My jQuery plugin</title>
<script src="jquery.js"></script>
<script>
$(function ()
{
$('.editable').txtEdit();
});
(function($){
$.fn.txtEdit = function() {
var editable = $(this);
$(editable).live('click',
function ()
{
var txt = $('<div>').attr('class', 'txtEdit div');
var inp = $('<input>').attr({'class':'txtEdit txt',
'type':'text'})
.val($(this).html()).blur(function (){
if($(this).val().length != ''){
$(txt).replaceWith($(editable)
.html($(this).val()));
}
else{ alert("Cannot contain empty value!")}
}).keydown(function (e){
if(e.keyCode == 13 || e.keyCode == 9){
e.preventDefault();
$(this).trigger('blur');
}
}).appendTo($(txt));
$(this).replaceWith(txt);
}
);
};
})(jQuery);
</script>
</head>
<body>
<div class="editable">this is editable div</div>
</body>
</html>
Anyone any ideas??
Regards,
add
inp.focus();
after
$(this).replaceWith(txt);
Because your div is created after focus action, which is wrong. You should display the div and then focus on input.
Instead of chaining the focus add this after creating the input box.
inp.focus();
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