I would like to have some functionality by which if I write
<textarea maxlength="50"></textarea>
<textarea maxlength="150"></textarea>
<textarea maxlength="250"></textarea>
it will automatically impose the maxlength on the textArea. If possible please do not provide the solution in jQuery.
Note: This can be done if I do something like this:
<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">
function imposeMaxLength(Event, Object, MaxLen)
{
return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}
Copied from What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?
But the point is I don't want to write onKeyPress and onKeyUp every time I declare a textArea.
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA');
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
};
}
I know you want to avoid jQuery, but as the solution requires JavaScript, this solution (using jQuery 1.4) is the most consise and robust.
Inspired by, but an improvement over Dana Woodman's answer:
Changes from that answer are: Simplified and more generic, using jQuery.live and also not setting val if length is OK (leads to working arrow-keys in IE, and noticable speedup in IE):
// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').live('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
EDIT: Updated version for jQuery 1.7+, using on instead of live
// Get all textareas that have a "maxlength" property. Now, and when later adding HTML using jQuery-scripting:
$('textarea[maxlength]').on('keyup blur', function() {
// Store the maxlength and value of the field.
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
// Trim the field if it has content over the maxlength.
if (val.length > maxlength) {
$(this).val(val.slice(0, maxlength));
}
});
Update Use Eirik's solution using .live() instead as it is a bit more robust.
Even though you wanted a solution that wasn't using jQuery, I thought I'd add one in for anyone finding this page via Google and looking for a jQuery-esque solution:
$(function() {
// Get all textareas that have a "maxlength" property.
$('textarea[maxlength]').each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field.
var maxlength = $textarea.attr('maxlength');
var val = $textarea.val();
// Trim the field if it has content over the maxlength.
$textarea.val(val.slice(0, maxlength));
// Bind the trimming behavior to the "keyup" event.
$textarea.bind('keyup', function() {
$textarea.val($textarea.val().slice(0, maxlength));
});
});
});
Hope that is useful to you Googlers out there...
HTML5 adds a maxlength attribute to the textarea element, like so:
<!DOCTYPE html>
<html>
<body>
<form action="processForm.php" action="post">
<label for="story">Tell me your story:</label><br>
<textarea id="story" maxlength="100"></textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is currently supported in Chrome 13, FF 5, and Safari 5. Not surprisingly, this is not supported in IE 9. (Tested on Win 7)
This solution avoids the issue in IE where the last character is removed when a character in the middle of the text is added. It also works fine with other browsers.
$("textarea[maxlength]").keydown( function(e) {
var key = e.which; // backspace = 8, delete = 46, arrows = 37,38,39,40
if ( ( key >= 37 && key <= 40 ) || key == 8 || key == 46 ) return;
return $(this).val().length < $(this).attr( "maxlength" );
});
My form validation then deals with any issues where the user may have pasted (only seems to be a problem in IE) text exceeding the maximum length of the textarea.
This is some tweaked code I've just been using on my site. It is improved to display the number of remaining characters to the user.
(Sorry again to OP who requested no jQuery. But seriously, who doesn't use jQuery these days?)
$(function() {
// Get all textareas that have a "maxlength" property.
$("textarea[maxlength]").each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field
var maxlength = $textarea.attr("maxlength");
// Add a DIV to display remaining characters to user
$textarea.after($("<div>").addClass("charsRemaining"));
// Bind the trimming behavior to the "keyup" & "blur" events (to handle mouse-based paste)
$textarea.on("keyup blur", function(event) {
// Fix OS-specific line-returns to do an accurate count
var val = $textarea.val().replace(/\r\n|\r|\n/g, "\r\n").slice(0, maxlength);
$textarea.val(val);
// Display updated count to user
$textarea.next(".charsRemaining").html(maxlength - val.length + " characters remaining");
}).trigger("blur");
});
});
Has NOT been tested with international multi-byte characters, so I'm not sure how it works with those exactly.
Also add the following event to deal with pasting into the textarea:
...
txts[i].onkeyup = function() {
...
}
txts[i].paste = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if (this.value.length + window.clipboardData.getData("Text").length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
...
The maxlength attribute is supported in Internet Explorer 10, Firefox, Chrome, and Safari.
Note: The maxlength attribute of the <textarea> tag is not supported in Internet Explorer 9 and earlier versions, or in Opera.
from HTML maxlength Attribute w3schools.com
For IE8 or earlier versions you have to use the following
//only call this function in IE
function maxLengthLimit($textarea){
var maxlength = parseInt($textarea.attr("maxlength"));
//in IE7,maxlength attribute can't be got,I don't know why...
if($.browser.version=="7.0"){
maxlength = parseInt($textarea.attr("length"));
}
$textarea.bind("keyup blur",function(){
if(this.value.length>maxlength){
this.value=this.value.substr(0,maxlength);
}
});
}
P.S.
The maxlength attribute of the <input> tag is supported in all major browsers.
from HTML maxlength Attribute w3schools.com
You can use jQuery to make it easy and clear
JSFiddle DEMO
<textarea id="ta" max="10"></textarea>
<script>
$("#ta").keypress(function(e){
var k = e.which==0 ? e.keyCode : e.which;
//alert(k);
if(k==8 || k==37 || k==39 || k==46) return true;
var text = $(this).val();
var maxlength = $(this).attr("max");
if(text.length >= maxlength) {
return false;
}
return true;
});
</script>
It is tested in Firefox, Google Chrome and Opera
Better Solution compared to trimming the value of the textarea.
$('textarea[maxlength]').live('keypress', function(e) {
var maxlength = $(this).attr('maxlength');
var val = $(this).val();
if (val.length > maxlength) {
return false;
}
});
Small problem with code above is that val() does not trigger change() event, so if you using backbone.js (or another frameworks for model binding), model won't be updated.
I'm posting the solution worked great for me.
$(function () {
$(document).on('keyup', '.ie8 textarea[maxlength], .ie9 textarea[maxlength]', function (e) {
var maxLength = $(this).attr('maxlength');
if (e.keyCode > 47 && $(this).val().length >= maxLength) {
$(this).val($(this).val().substring(0, maxLength)).trigger('change');
}
return true;
});
});
I implemented maxlength behaviour on textarea recently, and run into problem described in this question: Chrome counts characters wrong in textarea with maxlength attribute.
So all implementations listed here will work little buggy. To solve this issue I add .replace(/(\r\n|\n|\r)/g, "11") before .length. And kept it in mind when cuting string.
I ended with something like this:
var maxlength = el.attr("maxlength");
var val = el.val();
var length = val.length;
var realLength = val.replace(/(\r\n|\n|\r)/g, "11").length;
if (realLength > maxlength) {
el.val(val.slice(0, maxlength - (realLength - length)));
}
Don't sure if it solves problem completely, but it works for me for now.
Try this jQuery which works in IE9, FF, Chrome and provides a countdown to users:
$("#comments").bind("keyup keydown", function() {
var max = 500;
var value = $(this).val();
var left = max - value.length;
if(left < 0) {
$(this).val( value.slice(0, left) );
left = 0;
}
$("#charcount").text(left);
});
<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>
Try to use this code example:
$("#TextAreaID1").bind('input propertychange', function () {
var maxLength = 4000;
if ($(this).val().length > maxLength) {
$(this).val($(this).val().substring(0, maxLength));
}
});
2022 Update
You can set the HTML attribute for "maxlength" with the property maxLength (note the uppercase L). You might end up on this page if you were trying to use maxlength (all lowercase) and it wasn't working.
textareaElement1.maxLength = 50;
textareaElement2.maxLength = 150;
textareaElement3.maxLength = 250;
If you wanted to programmatically do it to all existing textareas, you could just iterate over a getElementsByTagName result:
const textAreas = document.getElementsByTagName('textarea');
for (const element of textAreas) {
element.maxLength = 150;
}
This is much easier:
<textarea onKeyPress="return ( this.value.length < 1000 );"></textarea>
Related
It's well-documented that different browsers treat newlines in text areas differently with regards to maxlength. For example, the snippet below will behave differently in Chrome versus Firefox if you use newlines.
My problem is that I need to allow users to enter newlines and I need to show them how many characters they have left. I could detect their browser type, but that's brittle and is a known antipattern. Is there a way to use feature detection to do this properly? Or should I still just avoid maxlength? Note that my question is not jQuery-specific, I just used jQuery in my examples for the sake of simplicity in showing what was happening. Note that I have an example already of a workaround without maxlength (see below), but it doesn't translate well across frameworks like ember where you want to avoid using jquery hacks.
Maxlength issue (try with Firefox, Chrome, and type at least one newline
$('.t').on('input',function(){
$('.x').html($('.t').val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="t" rows=3 maxlength=10></textarea>
<br>
chars typed: <span class="x"></span>
Without maxlength workaround (gross)
$('.t').on('input', function(){
let maxLength = 10;
let val = $('.t').val();
$('.t').val((val && val.length) ? val.substring(0,maxLength) : val);
$('.x').html($('.t').val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="t" rows=3></textarea>
Chars typed: <span class='x'></span>
You can use keydown and keyup events and regular expression which will replace all new lines characters with empty string. Than in the keydown event suppress type-in new character when the maxLength is reached, and in the keyup event display the number of characters left:
var maxLength = 10;
var navKeys = [8,46,27,38,40,33,34,13,37,39];
$(".x").html(maxLength);
$("textarea")
.on("keydown", function(e){
// Get value without new lines
var val = $(this).val().replace(/\n|\r/g, "");
// Allow nav keys
if(navKeys.indexOf(e.keyCode) !== -1) {
return true;
}
// Do not allow type in another char
if(val.length >= maxLength) {
e.preventDefault();
return;
}
})
.on("keyup", function(e) {
// Get value without new lines
var val = $(this).val().replace(/\n|\r/g, "");
$(".x").html(maxLength - val.length);
// Check the max length
if(val.length > maxLength) {
$(this).val(val.substr(0,maxLength));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<br/>
chars typed: <span class="x"></span>
This worked for me in FF and also in Chrome.
I think the best choice is that you implement your own maxLength.
Something like this:
var element = document.getElementById('textarea'),
maxLength = 10;
var trim = function() {
if(element.value.length >= maxLength) {
element.value = element.value.substring(0, maxLength);
}
};
// for older IE
element.onkeydown = function() {
setTimeout(trim, 1);
};
// browser support: CH, IE 9+, FF 4.0, SF 5.0, OP
element.oninput = trim;
<textarea rows="3" id="textarea"></textarea>
How can I get the caret position from within an input field?
I have found a few bits and pieces via Google, but nothing bullet proof.
Basically something like a jQuery plugin would be ideal, so I could simply do
$("#myinput").caretPosition()
Easier update:
Use field.selectionStart example in this answer.
Thanks to #commonSenseCode for pointing this out.
Old answer:
Found this solution. Not jquery based but there is no problem to integrate it to jquery:
/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
// Return results
return iCaretPos;
}
Use selectionStart. It is compatible with all major browsers.
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />
This works only when no type is defined or type="text" or type="textarea" on the input.
I've wrapped the functionality in bezmax's answer into jQuery if anyone wants to use it.
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
Got a very simple solution.
Try the following code with verified result-
<html>
<head>
<script>
function f1(el) {
var val = el.value;
alert(val.slice(0, el.selectionStart).length);
}
</script>
</head>
<body>
<input type=text id=t1 value=abcd>
<button onclick="f1(document.getElementById('t1'))">check position</button>
</body>
</html>
I'm giving you the fiddle_demo
There is now a nice plugin for this: The Caret Plugin
Then you can get the position using $("#myTextBox").caret() or set it via $("#myTextBox").caret(position)
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.
var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;
// and if you want to know if there is a selection or not inside your input:
if (input.selectionStart != input.selectionEnd)
{
var selectionValue =
input.value.substring(input.selectionStart, input.selectionEnd);
}
Perhaps you need a selected range in addition to cursor position. Here is a simple function, you don't even need jQuery:
function caretPosition(input) {
var start = input[0].selectionStart,
end = input[0].selectionEnd,
diff = end - start;
if (start >= 0 && start == end) {
// do cursor position actions, example:
console.log('Cursor Position: ' + start);
} else if (start >= 0) {
// do ranged select actions, example:
console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
}
}
Let's say you wanna call it on an input whenever it changes or mouse moves cursor position (in this case we are using jQuery .on()). For performance reasons, it may be a good idea to add setTimeout() or something like Underscores _debounce() if events are pouring in:
$('input[type="text"]').on('keyup mouseup mouseleave', function() {
caretPosition($(this));
});
Here is a fiddle if you wanna try it out: https://jsfiddle.net/Dhaupin/91189tq7/
const inpT = document.getElementById("text-box");
const inpC = document.getElementById("text-box-content");
// swch gets inputs .
var swch;
// swch if corsur is active in inputs defaulte is false .
var isSelect = false;
var crnselect;
// on focus
function setSwitch(e) {
swch = e;
isSelect = true;
console.log("set Switch: " + isSelect);
}
// on click ev
function setEmoji() {
if (isSelect) {
console.log("emoji added :)");
swch.value += ":)";
swch.setSelectionRange(2,2 );
isSelect = true;
}
}
// on not selected on input .
function onout() {
// الافنت اون كي اب
crnselect = inpC.selectionStart;
// return input select not active after 200 ms .
var len = swch.value.length;
setTimeout(() => {
(len == swch.value.length)? isSelect = false:isSelect = true;
}, 200);
}
<h1> Try it !</h1>
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box-content" size="20" value="content">
<button onclick="setEmoji()">emogi :) </button>
The solution is .selectionStart:
var input = document.getElementById('yourINPUTid');
input.selectionEnd = input.selectionStart = yourDESIREDposition;
input.focus();
If .selectionEnd is not assiged, some text (S-->E) will be selected.
.focus() is required when the focus is lost; when you trigger your code (onClick).
I only tested this in Chrome.
If you want more complicated solutions, you have to read the other answers.
I have the following code (pulled from this question) for setting a character limit on textareas.
function maxLength(el) {
if (!("maxLength" in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
var maxtext = document.getElementsByClassName("maxtext");
for (var i = 0; i < maxtext.length; i++) {
maxLength(maxtext[i]);
}
And an example of my html for textareas:
<textarea maxlength="150" class="maxtext"></textarea>
This all works just fine in Firefox and Chrome. In IE7+, it will stop me if I type up to the limit, but I'm then able to copy/paste text without restriction.
Any way to modify this script to prevent copy/pasting beyond the max character limit?
Listen for the onpaste event. Once the event fires, grab the text from the clipboard and manipulate it how you like.
HTML
<textarea id="test" maxlength="10" class="maxtext"></textarea>
JAVASCRIPT
var test = document.getElementById("test");
test.onpaste = function(e){
//do some IE browser checking for e
var max = test.getAttribute("maxlength");
e.clipboardData.getData('text/plain').slice(0, max);
};
EXAMPLE
You could listen to the onchange event to check the content length, if exceeds the limit then subtract it.
How can I get the caret position from within an input field?
I have found a few bits and pieces via Google, but nothing bullet proof.
Basically something like a jQuery plugin would be ideal, so I could simply do
$("#myinput").caretPosition()
Easier update:
Use field.selectionStart example in this answer.
Thanks to #commonSenseCode for pointing this out.
Old answer:
Found this solution. Not jquery based but there is no problem to integrate it to jquery:
/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
// Return results
return iCaretPos;
}
Use selectionStart. It is compatible with all major browsers.
document.getElementById('foobar').addEventListener('keyup', e => {
console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />
This works only when no type is defined or type="text" or type="textarea" on the input.
I've wrapped the functionality in bezmax's answer into jQuery if anyone wants to use it.
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
Got a very simple solution.
Try the following code with verified result-
<html>
<head>
<script>
function f1(el) {
var val = el.value;
alert(val.slice(0, el.selectionStart).length);
}
</script>
</head>
<body>
<input type=text id=t1 value=abcd>
<button onclick="f1(document.getElementById('t1'))">check position</button>
</body>
</html>
I'm giving you the fiddle_demo
There is now a nice plugin for this: The Caret Plugin
Then you can get the position using $("#myTextBox").caret() or set it via $("#myTextBox").caret(position)
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if (document.selection) {
// IE
input.focus();
}
return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
}
})(jQuery);
There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.
var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;
// and if you want to know if there is a selection or not inside your input:
if (input.selectionStart != input.selectionEnd)
{
var selectionValue =
input.value.substring(input.selectionStart, input.selectionEnd);
}
Perhaps you need a selected range in addition to cursor position. Here is a simple function, you don't even need jQuery:
function caretPosition(input) {
var start = input[0].selectionStart,
end = input[0].selectionEnd,
diff = end - start;
if (start >= 0 && start == end) {
// do cursor position actions, example:
console.log('Cursor Position: ' + start);
} else if (start >= 0) {
// do ranged select actions, example:
console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
}
}
Let's say you wanna call it on an input whenever it changes or mouse moves cursor position (in this case we are using jQuery .on()). For performance reasons, it may be a good idea to add setTimeout() or something like Underscores _debounce() if events are pouring in:
$('input[type="text"]').on('keyup mouseup mouseleave', function() {
caretPosition($(this));
});
Here is a fiddle if you wanna try it out: https://jsfiddle.net/Dhaupin/91189tq7/
const inpT = document.getElementById("text-box");
const inpC = document.getElementById("text-box-content");
// swch gets inputs .
var swch;
// swch if corsur is active in inputs defaulte is false .
var isSelect = false;
var crnselect;
// on focus
function setSwitch(e) {
swch = e;
isSelect = true;
console.log("set Switch: " + isSelect);
}
// on click ev
function setEmoji() {
if (isSelect) {
console.log("emoji added :)");
swch.value += ":)";
swch.setSelectionRange(2,2 );
isSelect = true;
}
}
// on not selected on input .
function onout() {
// الافنت اون كي اب
crnselect = inpC.selectionStart;
// return input select not active after 200 ms .
var len = swch.value.length;
setTimeout(() => {
(len == swch.value.length)? isSelect = false:isSelect = true;
}, 200);
}
<h1> Try it !</h1>
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box-content" size="20" value="content">
<button onclick="setEmoji()">emogi :) </button>
The solution is .selectionStart:
var input = document.getElementById('yourINPUTid');
input.selectionEnd = input.selectionStart = yourDESIREDposition;
input.focus();
If .selectionEnd is not assiged, some text (S-->E) will be selected.
.focus() is required when the focus is lost; when you trigger your code (onClick).
I only tested this in Chrome.
If you want more complicated solutions, you have to read the other answers.
This question has been asked in a few different formats but I can't get any of the answers to work in my scenario.
I am using jQuery to implement command history when user hits up/down arrows. When up arrow is hit, I replace the input value with previous command and set focus on the input field, but want the cursor always to be positioned at the end of the input string.
My code, as is:
$(document).keydown(function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
var input = self.shell.find('input.current:last');
switch(key) {
case 38: // up
lastQuery = self.queries[self.historyCounter-1];
self.historyCounter--;
input.val(lastQuery).focus();
// and it continues on from there
How can I force the cursor to be placed at the end of 'input' after focus?
Looks like clearing the value after focusing and then resetting works.
input.focus();
var tmpStr = input.val();
input.val('');
input.val(tmpStr);
It looks a little odd, even silly, but this is working for me:
input.val(lastQuery);
input.focus().val(input.val());
Now, I'm not certain I've replicated your setup. I'm assuming input is an <input> element.
By re-setting the value (to itself) I think the cursor is getting put at the end of the input. Tested in Firefox 3 and MSIE7.
Hope this help you:
var fieldInput = $('#fieldName');
var fldLength= fieldInput.val().length;
fieldInput.focus();
fieldInput[0].setSelectionRange(fldLength, fldLength);
Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
It uses setSelectionRange if supported, else has a solid fallback.
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;
});
};
Then you can just do:
input.putCursorAtEnd();
Ref: #will824 Comment, This solution worked for me with no compatibility issues. Rest of solutions failed in IE9.
var input = $("#inputID");
var tmp = input.val();
input.focus().val("").blur().focus().val(tmp);
Tested and found working in:
Firefox 33
Chrome 34
Safari 5.1.7
IE 9
What about in one single line...
$('#txtSample').focus().val($('#txtSample').val());
This line works for me.
2 artlung's answer:
It works with second line only in my code (IE7, IE8; Jquery v1.6):
var input = $('#some_elem');
input.focus().val(input.val());
Addition: if input element was added to DOM using JQuery, a focus is not set in IE. I used a little trick:
input.blur().focus().val(input.val());
I know this answer comes late, but I can see people havent found an answer. To prevent the up key to put the cursor at the start, just return false from the method handling the event. This stops the event chain that leads to the cursor movement. Pasting revised code from the OP below:
$(document).keydown(function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
var input = self.shell.find('input.current:last');
switch(key) {
case 38: // up
lastQuery = self.queries[self.historyCounter-1];
self.historyCounter--;
input.val(lastQuery).focus();
// HERE IS THE FIX:
return false;
// and it continues on from there
I use code below and it works fine
function to_end(el) {
var len = el.value.length || 0;
if (len) {
if ('setSelectionRange' in el) el.setSelectionRange(len, len);
else if ('createTextRange' in el) {// for IE
var range = el.createTextRange();
range.moveStart('character', len);
range.select();
}
}
}
It will be different for different browsers:
This works in ff:
var t =$("#INPUT");
var l=$("#INPUT").val().length;
$(t).focus();
var r = $("#INPUT").get(0).createTextRange();
r.moveStart("character", l);
r.moveEnd("character", l);
r.select();
More details are in these articles here at SitePoint, AspAlliance.
like other said, clear and fill worked for me:
var elem = $('#input_field');
var val = elem.val();
elem.focus().val('').val(val);
set the value first. then set the focus. when it focuses, it will use the value that exists at the time of focus, so your value must be set first.
this logic works for me with an application that populates an <input> with the value of a clicked <button>. val() is set first. then focus()
$('button').on('click','',function(){
var value = $(this).attr('value');
$('input[name=item1]').val(value);
$('input[name=item1]').focus();
});
I have found the same thing as suggested above by a few folks. If you focus() first, then push the val() into the input, the cursor will get positioned to the end of the input value in Firefox,Chrome and IE. If you push the val() into the input field first, Firefox and Chrome position the cursor at the end, but IE positions it to the front when you focus().
$('element_identifier').focus().val('some_value')
should do the trick (it always has for me anyway).
At the first you have to set focus on selected textbox object and next you set the value.
$('#inputID').focus();
$('#inputID').val('someValue')
function focusCampo(id){
var inputField = document.getElementById(id);
if (inputField != null && inputField.value.length != 0){
if (inputField.createTextRange){
var FieldRange = inputField.createTextRange();
FieldRange.moveStart('character',inputField.value.length);
FieldRange.collapse();
FieldRange.select();
}else if (inputField.selectionStart || inputField.selectionStart == '0') {
var elemLen = inputField.value.length;
inputField.selectionStart = elemLen;
inputField.selectionEnd = elemLen;
inputField.focus();
}
}else{
inputField.focus();
}
}
$('#urlCompany').focus(focusCampo('urlCompany'));
works for all ie browsers..
Here is another one, a one liner which does not reassign the value:
$("#inp").focus()[0].setSelectionRange(99999, 99999);
function CurFocus()
{
$('.txtEmail').focus();
}
function pageLoad()
{
setTimeout(CurFocus(),3000);
}
window.onload = pageLoad;
The answer from scorpion9 works. Just to make it more clear see my code below,
<script src="~/js/jquery.js"></script>
<script type="text/javascript">
$(function () {
var input = $("#SomeId");
input.focus();
var tmpStr = input.val();
input.val('');
input.val(tmpStr);
});
</script>
var prevInputVal = $('#input_id').val();
$('#input_id').val('').focus().val(prevInputVal)
Store input previous value in a variable -> empty input value -> focus input -> reassign original value SIMPLE !
It will focus with mouse point
$("#TextBox").focus();