什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?


当前回答

设置光标时,点击文本区域的文本结束… 这段代码的变体是…也工作!Firefox, IE, Safari, Chrome..

在服务器端代码中:

txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")

在Javascript中:

function sendCursorToEnd(obj) {
    var value =  $(obj).val(); //store the value of the element
    var message = "";
    if (value != "") {
        message = value + "\n";
     };
    $(obj).focus().val(message);
    $(obj).unbind();
 }

其他回答

如果输入字段只需要一个静态默认值,我通常用jQuery这样做:

$('#input').focus().val('Default value');

这似乎在所有浏览器中都有效。

仍然需要中间变量,(参见var val=) 否则光标的行为很奇怪,我们需要它在最后。

<body onload="document.getElementById('userinput').focus();">
<form>
<input id="userinput" onfocus="var val=this.value; this.value=''; this.value= val;"
         class=large type="text" size="10" maxlength="50" value="beans" name="myinput">
</form>
</body>
var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);

试试这个,它对我很有效:

//input is the input element

input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.  

为了让光标移动到最后,输入必须先有焦点,然后当值改变时,它才会移动到最后。如果你将.value设置为相同的值,它在chrome中不会改变。

<input id="input_1">
<input id="input_2" type="hidden">

<script type="text/javascript">
//save input_1 value to input_2
$("#input_2").val($("#input_1").val());

//empty input_1 and add the saved input_2 into input_1
$("#input_1").val("").val($("#input_2").val()).focus();
</script>