Why Text Boxes inserted with jquery lose focus?

I have a html file. I create text boxes with jquery. And after creating text boxes they lose focus and i can't write on them. This is my code.

<html>
<head>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".txt").click(function(){
            var value = $(this).text();
            var html = "<input type='text' class='txtbox' value='"+value+"'/>";
            $(this).html(html); 
        });
    });
</script>
<style type="text/css">
    div.txt{
        display: inline-block;
        border:1px red solid;
        width:150px;
        height: 30px;
        margin:1px;
    }
    div.btn{
        display:block;
        background-color: darkblue;
        color:white;
        padding:5px;
        text-align: center;
        width:100;
        cursor: default;
    }
    input[type='text'].txtbox{
        width: 100%;
        height: 100%;
        background-color: yellow;
        border:none;
        color:black;
        font-weight: bold;
    }
</style>
</head>
<body>
    <div class="txt">PARIS</div>
    <div class="txt">LONDON</div>
</body>

</html>

I can't solve this. I am new in jQuery. What is the problem?

Answers


Problem with your code is that as soon as html is replaced the focus is removed.

So, I would recommend you to add an jQuery object and use its focus(). to set focus back to textbox which was added.

$(document).ready(function () {
    $(".txt").click(function () {
        var value = $(this).text();
        var txtBox = $("<input type='text' class='txtbox' />")
            .val(value);
        $(this).html(txtBox);
        txtBox.focus()
    });
});

DEMO


When you click on them, the click event fires on the the element that is a member of class txt. The input is promptly removed and replaced with a new one that does not have the focus.

Test the event's target property to make sure that the txt element is clicked directly and not the input.

$(".txt").click(function(evt) {
    if (evt.target === this) {
        var value = $(this).text();
        var html = "<input type='text' class='txtbox' value='" + value + "'/>";
        $(this).html(html);
    }
}

Need Your Help

Using AnsiString like byte of array in Delphi XE4

string delphi delphi-xe indy10

Trying to move Delphi 2007 project to XE4. In Delphi 2007 I was using function that reads byte array from socket using Indy directly. I passed AnsiString casted to array of byte to var parameter of...