javascript - maxLength in IE8 - javascript

Using a javascript function to prevent exceeding the length of a textfield, but to still allow pasting & editing within it. Needs to work in IE8 & Firefox.
$(function() {
var helper = document.createElement('textarea');
//if (!('maxLength' in helper)) {
var supportsInput = 'oninput' in helper,
ev = supportsInput ? 'input' : 'propertychange paste keyup',
handler = function() {
var maxlength = +$(this).attr('maxlength');
if (this.value.length > maxlength) {
this.value = this.value.substring(0, maxlength);
}
};
$('textarea[maxlength]').on(ev, supportsInput ? handler : function() {
var that = this;
setTimeout(function() {
handler.call(that);
}, 0);
});
//}
});
It works okay if the text is on one line (testing with maxLength = 25). However, it doesn't do carriage returns & line feeds or account for them properly.
For example, if I enter the following text on one line:
1111122222333334444455555
it uses all 25 characters.
However, if I enter text on each line & hit enter, this is what I am able to enter:
11111
22222
33333
4444
Which is only 22 characters. I know that it is detecting a carriage return, because when I put in:
11111
a character counter shows 5. When I hit the enter key, the counter goes to 6, if I enter 22222 the counter is now 11.
The code I'm using to count the characters is:
$("#myTextArea").keyup(function() {
var j = $(this).val().length;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
I thought the issue might be some code I put in to resize the TextArea automatically, but it isn't. I'm sure I am just missing something on the code & would appreciate input on what I'm doing wrong & haven't seem to have figured out yet.

I stumbled upon the answer myself. It turns out the character counter I was using was not accurately counting the line breaks in the <textarea>.
Although I was using IE8, I found the answer in a question about Chrome counting characters wrong in textarea with maxLength attribute. That question is here.
The code I used before:
$("#myTextArea").keyup(function() {
var j = $(this).val().length;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
has been modified to:
$("#myTextArea").keyup(function() {
var x = $("#myTextArea").val();
var newLines = x.match(/(\r\n|\n|\r)/g);
var addition = 0;
if (newLines != null) {
addition = newLines.length;
}
var j = x.length + addition;
var i = 25 - j;
$("#charsUsed").text( j );
$("#charsLeft").text( i );
});
The embedded new lines must be transmitted as a CR LF pair - actually 2 characters. Thanks to the posters in the other thread for their help.

Related

Force first letter uppercase in input field

I'm practicing some JavaScript and would love to hear your thoughts regarding this script I wrote. I've managed to make this work. The script makes the first letter of the input value uppercase using the script below. I'm just wondering if this is a good method of doing this/if my steps are in good order just to get better
love to hear more ways of doing so, even making an option to eliminate the caps-lock via keyboard thanks,
// my input var
var strInput =document.querySelector("#inputText > input");
// my function and eventlistener
strInput.addEventListener('input',function() {
//upper case first letter with concatenate string input
var outputString = strInput.value.charAt(0).toUpperCase() + strInput.value.slice(1);
this.value = outputString;
});
As in the comments requested
Here is an example to bind the event to ALL text-inputs (except <textarea> and contenteditable="true")
var txtInputs = document.querySelectorAll("input[type='text'");
//just a simple validation if its not null, undefined or empty
if (txtInputs && txtInputs.length > 0) {
for (var i = 0; i < txtInputs.length; i++) {
var txtInput = txtInputs[i];
txtInput.addEventListener('input', function() {
var outputString = this.value.charAt(0).toUpperCase() + this.value.slice(1);
});
}

Javascript array length through user input

I have a problem in Javascript I want to make a form which have one input text field and one button when I click on the button window.prompt is called.
It will prompt depend upon my array length but I want array length get through input text field when I write 10 it will prompt 10 times when I write 2 it will prompt 2 times.
How can i write this type of query?
I tried this code but its not working.
words = new Array (4);
function a() {
for ( k = 0 ; k < words.length ; k = k + 1 ) {
words[ k ] = window.prompt( "Enter word # " + k, "" ) ;
}
}
Maybe you forgot to call your function a().
Some remarks about your code:
You don't have to specify an initial array size, e.g. words = [] or words = new Array() is enough.
Also k=k+1 is usually written as k++.
A remark about asking questions:
Use punctuation to make sentences! Your whole question is one sentence.
Hopefully it's just the snippet of code but I hope you are using var somewhere to declare all those variables.
Otherwise this should do the trick, however not sure what you are trying to achieve but this sounds like a bad user experience.
Here is the jsffidle http://jsfiddle.net/R2bCz/1/
function Handler(event) {
var count = event.target.value;
var i = 0;
var words = [];
var word;
for (; i < count; i++) {
word = window.prompt("Enter word # " + i, "");
words.push(word);
}
}
$("#multi").on("change", Handler);

Put line break after 10 characters in text area

I have a text area that can take 10000 characters. i want to put the line breaker on each line of the text area value after 10 character
something like this i want to achive
11111111 1
111 111 11
11 11 11 1
all above line has 10 characters each.
var start = 3
var times = 1;
$('.mydesc').keyup(function () {
var len = $(this).val().length;
if (len == start) {
this.value += '\n';
times = ++times;
start= ((start * 2) + start);
}
});
but doesn't work ..
Simplest solution is to always re-add all of the new-lines:
$('.mydesc').keyup(function () {
this.value = this.value
.replace(/[\n\r]+/g, "")
.replace(/(.{10})/g, "$1\n");
});
http://jsfiddle.net/s4cUz/
Something like this would do it:
http://jsfiddle.net/Zxuj7/
$('#test_textarea').keyup(function () {
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
var test = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(test);
});
However, be aware that it doesn't work that well with the "deleting" of characters. If you give it a go, you will notice that when you actually delete a character and the code runs, it will put you at the end of the textarea again (because its "overwriting" the value)
UPDATE:
You may actually be better formatting AFTER they have finished editing the textarea - i.e using blur();
$('#test_textarea').blur(function () {
// leaving the field... so lets try and format nicely now
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(new_stuff);
});
Although that doesn't do it in real time - it does work better when deleting/editing the contents
Enhanced version of Andrew Newby's script:
$('#test_textarea').keyup(function (e) {
if (e.keyCode === 8) return; // Backspace
var new_stuff = $(this).val();
new_stuff = new_stuff.replace(/[\n\r]+/g,""); // clean out newlines, so we dont get dups!
new_stuff = new_stuff.replace(/(.{10})/g,"$1\n");
$(this).val(new_stuff);
});
This actually ignores backspace key, so at least that interaction is preserved.

maxlength attribute is not working in IE [duplicate]

This question already has answers here:
Maxlength for text area doesn't work in IE
(4 answers)
Closed 9 years ago.
In my js file inside a function, i m preparing like this
var x = '<span class="someclass">
<textarea class="editField" maxlength="60">
</textarea>
</span>';
here i m restricting the textarea size by using maxlength attribute,
it is not working in IE.
maxlength is not supported on <textarea> in all browsers. In any case, I don't think it's ever a good idea to actually restrain users from typing what they want. Tell them that they're over the limit, but don't lock them out.
it wouldn't. IE10 now supports the HTML5 maxlength on a textarea. see here if you need to restrict length in previous IE versions then you'll need javascript for it.
Maxlength is not supported in IE, If you want to restrict your users from entering unlimited characters in IE, you would need to use javascript for that.
You could use the below script to limit users from entering maximum characters in textarea forIE.
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;
}
}
}
And Your textarea can be like:
<textarea maxlength="10"></textarea>
DEMO
The maxlength attribute is not standard for in HTML 4.01. It is defined in HTML5 though but I guess IE doesn't implement it. To make it work across all browsers you could use javascript. Here's an example.please check this it may helps you..thank you
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;
}
}
}
It's actually useless to restrain the user to type on his own end. This won't make any difference unless you don't test the length of what reaches the server (you really should).
I second what Kolink said, don't try to restrain the user from typing, but you can tell him that its input won't be accepted because it's exceeding.

jquery conversion for this javascript

I have the following code:
for (i=1; i<=len; i++) {
var optcheck = col+'|'+document.getElementById('color').options[i].value;
text = document.getElementById('color').options[i].text.split(' - ');
}
This is part of the original code from javascript. I have successfully converted much of the other stuff into jquery but I can't seem to figure out how to convert this into jquery.
Please note that col is just value I am passing when calling the function which is usually "16"
Here is what I got so far:
for (i=1; i<=len; i++) {
var optcheck = col+'|'+$('#color').val(i);
text = $('#color').val(i).text.split(' - ');
}
Also, the original code works fine in Chrome, Firefox, Opera and Safari but in IE (all version from 6 to 9) I get an error saying 'options[...].value' is not null or not an object
Thanks for the help!
You're mis-calling val.
Change it to $('#color option').eq(i).text() and $('#color option').eq(i).val()
$('#color option').each(function() {
var a = col + '|' + this.value,
b = this.text.split(' - ');
// do stuff with a and b
});

Categories