Search code examples
javascriptjquerypositioncursorfocus

jQuery textbox focus() place cursor anywhere


I have a javascript below:

function modify(value){
    $('.ajax').html($('.ajax input').val());
    $('.ajax').removeClass('ajax');
    $(value).addClass('ajax');
    $(value).html(
            '<input id="editbox"' + ' type="text" value="' + $(value).text() + '"/>');
    $('#editbox').focus();
}

Problem is that the cursor is placed at the beginning. Is there a solution I can place it wherever I want? F.e. if I click in the middle of the text I want the cursor to be there so I can edit the text from there on.

Thanks

EDIT: I can only modify my value if I navigate with the left/right arrows to the position I want. If I click into the middle, the cursor disappers.

Got It! Will paste code later


Solution

  • You can position the cursor at the end of the text:

    $(document).on('focus','#editbox',function(){        
         this.value = this.value;
    });