Javascript textfield value focus on - javascript

Environment:
Please use IE for testing it
Requirement:
I have an alert message which checks if user enters a value less than 8 digit - user wont be able to move to next field....he should remain on same field.
Problem:
Everything is fine with the functionality except one thing - when user enters any value in a textfield less than 8 digits he gets his foucs back in such a manner than the cursor moves to the first letter of the entered value whereas it should go back to the last letter of the entered valued.
Code:
<html>
<body>
<script>
function checkField(field) {
if (field.value.length < 8) {
// Toggle the active element's blur off and back on after the next blur
var active = document.activeElement;
if (active && active !== field) {
var blur = active.onblur || function(){};
active.onblur = function(){ active.onblur = blur };
}
field.focus();
alert("cannot be less than 8 digits");
}
}
</script>
<input type="text" id="test1" onblur='return checkField(this);'>
<br/>
<input type="text" id="test2" onblur='return checkField(this);'>
</tr>
</table>
</body>
</html>

It's a hack, but this works - add an onfocus listener to replace the value with itself, and IE will behave by putting the cursor at the end - onfocus="this.value = this.value;":
Used like this:
<input id="test1" type="text" value="whatever" onblur="return checkField(this);" onfocus="this.value = this.value;" />
If you ever plan to migrate to JQuery (which I recommend), check out this plugin:
// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea
// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
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;
});
};
})(jQuery);

Related

Javascript how to place cursor at end of input field text after inserting text? [duplicate]

What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element?
There's a simple way to get it working in most browsers.
this.selectionStart = this.selectionEnd = this.value.length;
However, due to the *quirks of a few browsers, a more inclusive answer looks more like this
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
Using jQuery (to set the listener, but it's not necessary otherwise)
$('#el').focus(function(){
var that = this;
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='el' type='text' value='put cursor at end'>
Using Vanilla JS (borrowing addEvent function from this answer)
// Basic cross browser addEvent
function addEvent(elem, event, fn){
if(elem.addEventListener){
elem.addEventListener(event, fn, false);
}else{
elem.attachEvent("on" + event,
function(){ return(fn.call(elem, window.event)); });
}}
var element = document.getElementById('el');
addEvent(element,'focus',function(){
var that = this;
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
<input id='el' type='text' value='put cursor at end'>
Quirks
Chrome has an odd quirk where the focus event fires before the cursor is moved into the field; which screws my simple solution up. Two options to fix this:
You can add a timeout of 0 ms (to defer the operation until the stack is clear)
You can change the event from focus to mouseup. This would be pretty annoying for the user unless you still kept track of focus. I'm not really in love with either of these options.
Also, #vladkras pointed out that some older versions of Opera incorrectly calculate the length when it has spaces. For this you can use a huge number that should be larger than your string.
Try this, it has worked for me:
//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.
For the cursor to be move to the end, the input has to have focus first, then when the value is changed it will goto the end. If you set .value to the same, it won't change in chrome.
I faced this same issue (after setting focus through RJS/prototype) in IE.
Firefox was already leaving the cursor at the end when there is already a value for the field. IE was forcing the cursor to the beginning of the text.
The solution I arrived at is as follows:
<input id="search" type="text" value="mycurrtext" size="30"
onfocus="this.value = this.value;" name="search"/>
This works in both IE7 and FF3 but doesn't work in modern browsers (see comments) as it is not specified that UA must overwrite the value in this case (edited in accordance with meta policy).
After hacking around with this a bit, I found the best way was to use the setSelectionRange function if the browser supports it; if not, revert to using the method in Mike Berrow's answer (i.e. replace the value with itself).
I'm also setting scrollTop to a high value in case we're in a vertically-scrollable textarea. (Using an arbitrary high value seems more reliable than $(this).height() in Firefox and Chrome.)
I've made it is as a jQuery plugin. (If you're not using jQuery I trust you can still get the gist easily enough.)
I've tested in IE6, IE7, IE8, Firefox 3.5.5, Google Chrome 3.0, Safari 4.0.4, Opera 10.00.
It's available on jquery.com as the PutCursorAtEnd plugin. For your convenience, the code for release 1.0 is as follows:
// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea
// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
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;
});
};
})(jQuery);
<script type="text/javascript">
function SetEnd(txt) {
if (txt.createTextRange) {
//IE
var FieldRange = txt.createTextRange();
FieldRange.moveStart('character', txt.value.length);
FieldRange.collapse();
FieldRange.select();
}
else {
//Firefox and Opera
txt.focus();
var length = txt.value.length;
txt.setSelectionRange(length, length);
}
}
</script>
This function works for me in IE9, Firefox 6.x, and Opera 11.x
It's 2019 and none of the methods above worked for me, but this one did, taken from https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/
function moveCursorToEnd(id) {
var el = document.getElementById(id)
el.focus()
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
<input id="myinput" type="text" />
Move cursor to end
I've tried the following with quite great success in chrome
$("input.focus").focus(function () {
var val = this.value,
$this = $(this);
$this.val("");
setTimeout(function () {
$this.val(val);
}, 1);
});
Quick rundown:
It takes every input field with the class focus on it, then stores the old value of the input field in a variable, afterwards it applies the empty string to the input field.
Then it waits 1 milisecond and puts in the old value again.
el.setSelectionRange(-1, -1);
https://codesandbox.io/s/peaceful-bash-x2mti
This method updates the HTMLInputElement.selectionStart, selectionEnd,
and selectionDirection properties in one call.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
In other js methods -1 usually means (to the) last character. This is the case for this one too, but I couldn't find explicit mention of this behavior in the docs.
Simple. When editing or changing values, first put the focus then set value.
$("#catg_name").focus();
$("#catg_name").val(catg_name);
Still the intermediate variable is needed, (see var val=)
else the cursor behaves strange, we need it at the end.
<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>
const end = input.value.length
input.setSelectionRange(end, end)
// 👇 scroll to the bottom if a textarea has long text
input.focus()
Try this one works with Vanilla JavaScript.
<input type="text" id="yourId" onfocus="let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">
In Js
document.getElementById("yourId").focus()
For all browsers for all cases:
function moveCursorToEnd(el) {
window.setTimeout(function () {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}, 1);
}
Timeout required if you need to move cursor from onFocus event handler
I like the accepted answer a lot, but it stopped working in Chrome. In Chrome, for the cursor to go to the end, input value needs to change. The solution is as follow:
<input id="search" type="text" value="mycurrtext" size="30"
onfocus="var value = this.value; this.value = null; this.value = value;" name="search"/>
document.querySelector('input').addEventListener('focus', e => {
const { value } = e.target;
e.target.setSelectionRange(value.length, value.length);
});
<input value="my text" />
In jQuery, that's
$(document).ready(function () {
$('input').focus(function () {
$(this).attr('value',$(this).attr('value'));
}
}
I just found that in iOS, setting textarea.textContent property will place the cursor at the end of the text in the textarea element every time. The behavior was a bug in my app, but seems to be something that you could use intentionally.
This problem is interesting. The most confusing thing about it is that no solution I found solved the problem completely.
+++++++ SOLUTION +++++++
You need a JS function, like this:
function moveCursorToEnd(obj) {
if (!(obj.updating)) {
obj.updating = true;
var oldValue = obj.value;
obj.value = '';
setTimeout(function(){ obj.value = oldValue; obj.updating = false; }, 100);
}
}
You need to call this guy in the onfocus and onclick events.
<input type="text" value="Test Field" onfocus="moveCursorToEnd(this)" onclick="moveCursorToEnd(this)">
IT WORKS ON ALL DEVICES AN BROWSERS!!!!
var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);
Taking some of the answers .. making a single-line jquery.
$('#search').focus().val($('#search').val());
If the input field just needs a static default value I usually do this with jQuery:
$('#input').focus().val('Default value');
This seems to work in all browsers.
While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.
The solution that works cross browser and for all input types is rather simple:
get and store the value of input in a variable
focus the input
set the value of input to the stored value
That way the cursor is at the end of the input element.
So all you'd do is something like this (using jquery, provided the element selector that one wishes to focus is accessible via 'data-focus-element' data attribute of the clicked element and the function executes after clicking on '.foo' element):
$('.foo').click(function() {
element_selector = $(this).attr('data-focus-element');
$focus = $(element_selector);
value = $focus.val();
$focus.focus();
$focus.val(value);
});
Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.
Super easy (you may have to focus on the input element)
inputEl = getElementById('inputId');
var temp = inputEl.value;
inputEl.value = '';
inputEl.value = temp;
Set the cursor when click on text area to the end of text...
Variation of this code is...ALSO works! for Firefox, IE, Safari, Chrome..
In server-side code:
txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")
In 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();
}
If you set the value first and then set the focus, the cursor will always appear at the end.
$("#search-button").click(function (event) {
event.preventDefault();
$('#textbox').val('this');
$("#textbox").focus();
return false;
});
Here is the fiddle to test
https://jsfiddle.net/5on50caf/1/
I wanted to put cursor at the end of a "div" element where contenteditable = true, and I got a solution with Xeoncross code:
<input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">
<div id="test" contenteditable="true">
Here is some nice text
</div>
And this function do magic:
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
Works fine for most browsers, please check it, this code puts text and put focus at the end of the text in div element (not input element)
https://jsfiddle.net/Xeoncross/4tUDk/
Thanks, Xeoncross
I also faced same problem. Finally this gonna work for me:
jQuery.fn.putCursorAtEnd = = function() {
return this.each(function() {
// Cache references
var $el = $(this),
el = this;
// Only focus if input isn't already
if (!$el.is(":focus")) {
$el.focus();
}
// If this function exists... (IE 9+)
if (el.setSelectionRange) {
// Double the length because Opera is inconsistent about whether a carriage return is one character or two.
var len = $el.val().length * 2;
// Timeout seems to be required for Blink
setTimeout(function() {
el.setSelectionRange(len, len);
}, 1);
} else {
// As a fallback, replace the contents with itself
// Doesn't work in Chrome, but Chrome supports setSelectionRange
$el.val($el.val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Chrome)
this.scrollTop = 999999;
});
};
This is how we can call this:
var searchInput = $("#searchInputOrTextarea");
searchInput
.putCursorAtEnd() // should be chainable
.on("focus", function() { // could be on any event
searchInput.putCursorAtEnd()
});
It's works for me in safari, IE, Chrome, Mozilla. On mobile devices I didn't tried this.
Check this solution!
//fn setCurPosition
$.fn.setCurPosition = function(pos) {
this.focus();
this.each(function(index, elem) {
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
});
return this;
};
// USAGE - Set Cursor ends
$('#str1').setCurPosition($('#str1').val().length);
// USAGE - Set Cursor at 7 position
// $('#str2').setCurPosition(7);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Set cursor at any position</p>
<p><input type="text" id="str1" value="my string here" /></p>
<p><input type="text" id="str2" value="my string here" /></p>
I took the best answers from here, and created a function that works well in Chrome.
You will need to wrap the logic in a timeout, because you have to wait for the focus to finish before accessing the selection
To place the cursor at the end, the selection start needs to be placed at the end
In order to scroll to the end of the input field, the scrollLeft needs to match the scrollWidth
/**
* Upon focus, set the cursor to the end of the text input
* #param {HTMLInputElement} inputEl - An HTML <input> element
*/
const setFocusEnd = (inputEl) => {
setTimeout(() => {
const { scrollWidth, value: { length } } = inputEl;
inputEl.setSelectionRange(length, length);
inputEl.scrollLeft = scrollWidth;
}, 0);
};
document
.querySelector('input')
.addEventListener('focus', (e) => setFocusEnd(e.target));
html, body {
width: 100%;
height: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
input:focus {
background-color: hsla(240, 100%, 95%, 1.0);
}
<input
type="text"
placeholder="Search..."
value="This is some really, really long text">
<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>

Is it possible to lock/focus the cursor to the last line of textarea?

Lets say we have a textarea in our html code.
This textarea contains some.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cursor Test</title>
</head>
<body>
<textarea class="text" cols="200" rows="40">
Some Random text.
More random text
> [fixed cursor position]
</textarea>
</body>
</html>
Is it possible to prevent to move the cursor from moving above or before the specified position? (in the code marked as [fixed cursor position])
I want still be able to write, but I don't want to exceed the start position. (either above or before the starting position -> [fixed cursor position])
So if the focus is on the textarea the cursor should move to its position, when typing. (onKeyPress, to still be able to select and mark text in the textarea)
In this case -> (at least) Line 3, Col 3
Can this be done in JavaScript or JQuery?
There is a little function which will help you:
jQuery.fn.lockCursor = function() {
return this.each(function() { //return the function for each object
if (this.setSelectionRange) { //check if function is available
var len = $(this).val().length * 2; //avoid problems with carriage returns in text
this.setSelectionRange(len, len);
} else {
$(this).val($(this).val()); //replace content with itself
//Will automatically set the cursor to the end
}
});
};
$('.text').keypress(function(){
$(this).lockCursor(); //execute function on keypress
});
Demo
Edit
I updated my code, to make it possible to edit the text, which has been added by myself:
var selectEnd; //global variable
jQuery.fn.lockCursor = function() {
return this.each(function() {
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
});
};
$('.text').focus(function(){
$(this).lockCursor();
selectEnd = $(this).val().length; //save original length of value
});
$('.text').keypress(function(){
if($(this)[0].selectionStart < selectEnd){ //cursor position is lower then initial position
$(this).lockCursor();
}
});
Explanation:
$(this)[0].selectionStart is necessary, because it must be only one element and not a set of elements provided by the jQuery-Object
Note: this solution may be not compatible to all browser and versions, depending on their support of the selectionStart -method
Demo 2
Reference
setSelectionRange

Programmatically focus on next input field in mobile safari

I have several input fields in line that acts like a crossword answer line:
Each square has its own input field. The reason for this is amongst other things that sometimes a square can be pre-populated. Now, on desktop browser the cursor jumps to the next input field whenever a char is entered. That works really well using something like:
$(this).next('input').focus();
But the problem on mobile safari (we test on ios) is that I don’t know how to automatically "jump" to the next input field programatically. The user can do it via the the "next" button, but is there a way to do this automatically?
I know that the focus() trigger has some limitations on ios, but I’ve also seen some workaround using synthesized clicks etc.
I found a workaround that might work for you.
Apparently IOS/Safari only "accepts" the focus when inside a touch event handler. I triggered a touch event and inserted the .focus() inside it. I tried this on my iPhone3S and iPhone5S with Safari and it works:
var focused = $('input:first'); //this is just to have a starting point
$('button').on('click', function () { // trigger touch on element to set focus
focused.next('input').trigger('touchstart'); // trigger touchstart
});
$('input').on('touchstart', function () {
$(this).focus(); // inside this function the focus works
focused = $(this); // to point to currently focused
});
Demo here
(press next button in demo)
Programmatically moving to the next input field in a mobile browser without dismissing the keyboard appears to be impossible. (This is terrible design, but it's what we have to work with.) However, a clever hack is to swap the input element positions, values, and attributes with Javascript so that it looks like you are moving to the next field when in fact you are still focused on the same element. Here is code for a jQuery plug-in that swaps the id, name, and value. You can adapt it to swap other attributes as necessary. Also be sure to fix up any registered event handlers.
$.fn.fakeFocusNextInput = function() {
var sel = this;
var nextel = sel.next();
var nextval = nextel.val();
var nextid = nextel.attr('id');
var nextname = nextel.attr('name');
nextel.val(sel.val());
nextel.attr('id', sel.attr('id'));
nextel.attr('name', sel.attr('name'));
sel.val(nextval);
sel.attr('id', nextid);
sel.attr('name', nextname);
// Need to remove nextel and not sel to retain focus on sel
nextel.remove();
sel.before(nextel);
// Could also return 'this' depending on how you you want the
// plug-in to work
return nextel;
};
Demo here: http://jsfiddle.net/EbU6a/194/
UIWebview has the property keyboardDisplayRequiresUserAction
When this property is set to true, the user must explicitly tap the elements in the web view to display the keyboard (or other relevant input view) for that element. When set to false, a focus event on an element causes the input view to be displayed and associated with that element automatically.
https://developer.apple.com/documentation/uikit/uiwebview/1617967-keyboarddisplayrequiresuseractio
I hope this is what you are looking for-
$(document).ready(function() {
$('input:first').focus(); //focus first input element
$('input').on('keyup', function(e) {
if(e.keyCode == 8) { //check if backspace is pressed
$(this).prev('input').focus();
return;
}
if($(this).val().length >= 1) { //for e.g. you are entering pin
if ($(this).hasClass("last")) {
alert("done");
return;
}
$(this).next('input').focus();
}
});
$('input').on('focus', function() {
if(!$(this).prev('input').val()){
$(this).prev('input').focus();
}
});
});
check code here-
https://jsbin.com/soqubal/3/edit?html,output
Add this line in your config file in ios section
preference name="KeyboardDisplayRequiresUserAction" value="false"
I encounter the same problem on safari ios. on login page, I programmatically focus on next input field after user input one sms code.
I trigger the auto focus on input change event. I fixed the problem by adding a delay.
For details, see the code below
<InputItem
value={item}
type='number'
maxLength={1}
ref={el => this[`focusInstRef${index}`] = el}
onChange={(value) => {
value&&index !== 5 && setTimeout(() => {this[`focusInstRef${index + 1}`].focus()}, 5);
vAppStore.setSmsCodeArr(value, index);}
}
/>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#hidebox {position:absolute; border: none; background:transparent;padding:1px;}
#hidebox:focus{outline: 0;}
</style>
</head>
<body>
<input type="text" maxlength="1" onkeyup="keyUp(this)" onkeydown="keyDown(this)" size="2" id="hidebox" at="1">
<input type="text" maxlength="1" size="2" id="mFirst" at="1" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mSecond" at="2" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mThird" at="3" onfocus="onFocus(this)"><input type="text" maxlength="1" size="2" id="mFourth" at="4" onfocus="onFocus(this)">
</li>
<script type="text/javascript">
window.onload = function() {
document.getElementById("mFirst").focus();
}
var array = ["mFirst","mSecond","mThird","mFourth"];
function keyUp(e) {
var curId = array[Number(e.getAttribute("at"))-1];
var nextId = array[Number(e.getAttribute("at"))];
var curval= e.value;
var letters = /^[0-9a-zA-Z]+$/;
if(e.value.match(letters)){
document.getElementById(curId).value = curval;
if(e.getAttribute("at") <= 3){
var nextPos = document.getElementById(nextId).offsetLeft;
e.setAttribute("at",Number(e.getAttribute("at"))+1);
e.style.left = nextPos+"px";
}
e.value = ""
}else {
e.value = "";
}
}
function keyDown(e) {
var curId = array[Number(e.getAttribute("at"))-1];
document.getElementById(curId).value = "";
}
function onFocus(e) {
document.getElementById("hidebox").focus();
document.getElementById("hidebox").setAttribute("at",Number(e.getAttribute("at")));
document.getElementById("hidebox").style.left = e.offsetLeft+"px";
document.getElementById("hidebox").style.top = e.offsetTop+"px";
}
</script>
</body>
</html>

Can input be limited to html <textarea>? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best way to emulate an HTML input “maxlength” attribute on an HTML textarea?
My question is can a <textarea > be configured only to accept a certain number of characters? I can do this in the following JavaScript, but the person for whom I am designing this page does not want a status field.
My current way of doing things is I have a <textarea > that is part of a form that uses a nice JavaScript function to fill a message in a status box.
I also read SO and found Alerts and sounds really aren't the way to alert people, so the following code changes background color (and restores when appropriate) when there is an error.
Here is that code:
// Checks Form element TransDesc for overruns past 255 characters.
function warnOverDescLen()
{
var misc_text =
document.forms["InvGenPayTickets"]["TransDesc"].value;
var alert_text =
"You cannot enter more than 255 characters. Please remove some information.";
var rc = true;
if(255 < misc_text.length)
{
document.forms["InvGenPayTickets"]["trans_status"].value
= alert_text;
misc_text = misc_text.substring(0, 253);
document.forms["InvGenPayTickets"]["TransDesc"].value
= misc_text;
document.forms["InvGenPayTickets"]["trans_status"].style.backgroundColor
= "pink";
}
else
{
document.forms["InvGenPayTickets"]["trans_status"].value
= "";
document.forms["InvGenPayTickets"]["trans_status"].style.backgroundColor
= "lightgoldenrodyellow";
}
return rc;
}
<textarea rows="4" cols="60" name="TransDesc" id="TransDesc"
onkeypress="return warnOverDescLen();" ></textarea>
<span style="color: #50081E; font-weight: bold">Status</span>
<br />
<input type=text name="trans_status" id="trans_status" maxwidth="50"
size="65" />
This is a solution for HTML5, not supported by IE9 or earlier (according to this):
<textarea maxlength="255"></textarea>
Since you probably can't drop support for IE9 (and maybe even IE8), it's recommended you couple that with JavaScript, preventing the default behavior for the keydown and paste events on the textarea, as standup75 suggested.
Here is how to do that with plain JavaScript:
<textarea id="txtarea" maxlength="255"></textarea>
<script>
var field = document.getElementById('txtarea');
if(field.addEventListener) {
field.addEventListener('keydown', enforceMaxlength);
field.addEventListener('paste', enforceMaxlength);
} else {
// IE6-8
field.attachEvent('onkeydown', enforceMaxlength);
field.attachEvent('onpaste', enforceMaxlength);
}
function enforceMaxlength(evt) {
var maxLength = 255;
if(this.value.length >= maxLength) {
evt.preventDefault()
}
}
</script>
http://jsfiddle.net/snJwn/
HTML5 offers the maxLength attribute. Otherwise, you'd need some javascript, in jQuery, you'd do something like
maxLength = 50;
$("textarea").on("keydown paste", function(e){
if ($(this).val().length>=maxLength) e.preventDefault();
});
you can use the maxlength="255" (it specifies the maximum number of characters allowed in the element.)
or you can also do this by the jquery here i found the tutorial
html
<textarea cols="30" rows="5" maxlength="10"></textarea>
jquery
jQuery(function($) {
// ignore these keys
var ignore = [8,9,13,33,34,35,36,37,38,39,40,46];
// use keypress instead of keydown as that's the only
// place keystrokes could be canceled in Opera
var eventName = 'keypress';
// handle textareas with maxlength attribute
$('textarea[maxlength]')
// this is where the magic happens
.live(eventName, function(event) {
var self = $(this),
maxlength = self.attr('maxlength'),
code = $.data(this, 'keycode');
// check if maxlength has a value.
// The value must be greater than 0
if (maxlength && maxlength > 0) {
// continue with this keystroke if maxlength
// not reached or one of the ignored keys were pressed.
return ( self.val().length < maxlength
|| $.inArray(code, ignore) !== -1 );
}
})
// store keyCode from keydown event for later use
.live('keydown', function(event) {
$.data(this, 'keycode', event.keyCode || event.which);
});
});
Live example

Getting caret position in IE works in one scenario, doesn't in another

I have an input element in HTML markup as below:
<input type="text" name="s" id="s" value="" />
I am changing the characters entered in this input element with Urdu ones (like a mini virtual keyboard), by using jQuery's keypress:
$("#s").keypress(function(e) {
var pos = getCaretPos('s');
// key-mapping logic here
});
I also have some buttons that help a user enter their desired Urdu character by clicking on a respective button. Thus:
// Process clicks on buttons with class=kb-letter
$(".kb-letter").click(function() {
var pos = getCaretPos('s');
// logic for entering Urdu characters in 's' here
});
This is the function for getting caret position. It returns the current caret position in s and the new character is then inserted at that position:
function getCaretPos(areaId) {
var txtArea = document.getElementById(areaId);
var pos = 0;
var br = (document.selection ? "ie" : ((txtArea.selectionStart || txtArea.selectionStart == '0') ? "ff" : false ) );
if (br == "ie") {
txtArea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtArea.value.length);
pos = range.text.length;
}
else if (br == "ff") {
pos = txtArea.selectionStart;
}
return pos;
}
Now, the above getCaretPos() works fine in Firefox 8 and Chrome 17 for both direct keyboard input in s and input using clicking on buttons; but on Internet Explorer 8, it works only for direct keyboard input. If I try entering a character using mouse clicks, it gets entered at location 0 because getCaretPos() always returns 0 in that case.
I have no idea what is going wrong. Do I need to call getCaretPos() in a different manner in response to mouse clicks for IE?
Never mind. I was using an unordered list with its <li>s posing as keyboard buttons. For some reason, IE was having problems with them. I swapped the <li>s for <button>s and now getCaretPos() is working all fine.

Categories

Resources