Set cursor position in an input text field

后端 未结 2 1453
失恋的感觉
失恋的感觉 2021-01-01 18:45

After a lot of search I found the following threads:

define cursor position in form input field

jQuery Set Cursor Position in Text Area

Unfortunately

2条回答
  •  梦毁少年i
    2021-01-01 19:05

    Inside your tag is where your JavaScript goes (although we prefer putting it in a separate file, so that no JavaScript lives on the HTML page itself).

    Inside that, you have a call to $(document).ready(), which passes a function() { ... }. Inside that function is all the code that will be executed when your document has loaded.

    Inside that function you have a call to $('#site').focus() which itself provides a function — this time one that will be called whenever the #site element gains focus. And presumably that's where you want to change the cursor position.

    So, taking the setCursor function from Set cursor at a length of 14 onfocus of a textbox you can put that anywhere in your and then inside that innermost function of yours you can write:

    if( this.value == this.defaultValue ) {
        $(this).val("http://");
    
        var node = $(this).get(0);
        setCursor(node,node.value.length);
    }
    

提交回复
热议问题