以下の基本的なjfiddleを組み立てました。何らかの理由で、セレクターは textarea ボックスを取得して値を設定するように機能しますが、セレクターは setSelectionRange 関数を使用するために機能しません。コンソールで、.setSelectionRange is not a function のエラーが表示されます。
コード (jfiddle を参照してください):
selector.setSelectionRange(carat,carat);
以下の基本的なjfiddleを組み立てました。何らかの理由で、セレクターは textarea ボックスを取得して値を設定するように機能しますが、セレクターは setSelectionRange 関数を使用するために機能しません。コンソールで、.setSelectionRange is not a function のエラーが表示されます。
コード (jfiddle を参照してください):
selector.setSelectionRange(carat,carat);
HTML:
<input type="search" value="Potato Pancakes" id="search">
Jクエリ:
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
$("#search").putCursorAtEnd();
小切手:
http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
あなたは私のために働くこれを試すことができます. これを使用して、個別の住所フィールドから住所を作成し、コピーして貼り付けます。
HTML
<div id="d_clip_container" style="position:relative">
(<a href="#" id="d_clip_button">copy to clipboard</a>)
</div>;
<textarea id="clip" rows="0" cols="0" style="border:none;height:0;width:0;"></textarea>
jQuery
$(document).ready(function() {
$('#d_clip_button').click(function() {
//get all the values of needed elements
var fName = $("#firstName").val();
var lName = $("#lastName").val();
var address = $("#Address").val();
var city = $("#City").val();
var state = $("#State").val();
var zip = $("#Zip").val();
//concatenate and set "clip" field with needed content
$('#clip').val(fName + " " + lName + "\n" + address + "\n" + city + ", " + state + " " + zip);
//Do it
if(copyToClipboard('#clip')) {
alert('text copied');
} else {
alert('copy failed');
}
});
});
function copyToClipboard(elem) {
// set focus to hidden element and select the content
$(elem).focus();
// select all the text therein
$(elem).select();
var succeed;
try {
succeed = document.execCommand("copy");
} catch(e) {
succeed = false;
}
// clear temporary content
$(target).val('');
return succeed;
}