I have issue wit javascript maxlength calculation.
Javascript
function charCount(characters) {
document.getElementById('citation').onkeyup = function () {
var s = this.value;
document.getElementById('sBann').innerHTML = (characters - s.length) + " characters left.";
};
}
JSP:
<div class="FormRow">
<textarea class="textAreaLarge" rows="20" cols="180" name="citation" id="citation" maxlength="<%=maxCitationLength%>" onKeyUp="charCount(<%=maxCitationLength%>);"><%=citation%></textarea>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
<strong><div id="sBann" class="minitext"><% if (citation != null) { %><%= (maxCitationLength-citation.length()) %><%} else {%><%= (maxCitationLength) %><%}%> characters left.</div></strong>
</div>
My textarea has a maxlength of 1650 which should include the spaces too.
I have a create page.
While I type something in UI it takes into account the end of line as 1 character and allows upto 1650 characters and prevents user from entering more and its fine.
But on the server side end of line is taken as 2 characters for CR and CF and though JS calculates 1650 the data gets inserted with CR an CF and the length in DB is > 1650 say for example 1680.
On the DB side this field is a clob so i have no issues even if it stores > 1650.
Now i have a edit screen where I have to display the same textarea and allow user to edit.
For the same example above where i entered 1650 but DB shows 1680, textarea in UI shows 1680 characters so the span on load which shows the no of charcters left is -20 because of the CR/CF value included on server side.
How do i deal with client side validation to include 2 characters for CR/CF?
its carriage return CR and line feed LF. on Windows, if you console.log() textarea value it will not return CR or \r it only \n, I'm not sure on mac os.
You have duplicate events
onKeyUp="charCount(<%=maxCitationLength%>);"
// and
document.getElementById('citation').onkeyup = function () {
call it only once, in element attribute or script tag.
And to count CR/LF as two char use regex
document.getElementById('citation').oninput = function(e) {
var maxChars = 20;
var sBann = document.getElementById('sBann');
var s = this.value;
// count linebreak
var lineBreaks = s.match(/(?!\n$)\n/g) || '';
var charCount = s.length + lineBreaks.length;
if (charCount > maxChars) {
this.value = s.slice(0, maxChars - lineBreaks.length);
sBann.innerHTML = "0 characters left.";
return false;
}
sBann.innerHTML = (maxChars - charCount) + " characters left.";
console.log('s: ' + (s.length - lineBreaks.length), '|', 'line break (x2): ' + lineBreaks.length * 2);
console.log('total: ' + charCount)
};
<div class="FormRow">
<textarea class="textAreaLarge" rows="10" cols="40" name="citation" id="citation" maxlength="20"></textarea>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
<strong><div id="sBann" class="minitext">20 characters left.</div></strong>
</div>
Consider the following.
$(function() {
function charactersLeft(el) {
var max = parseInt($(el).attr("maxLength"));
var cur = $(el).val().length;
return max - cur;
}
function allowType(el) {
var result = true;
if (charactersLeft(el) <= 0) {
result = false;
}
return result;
}
function myTrim(el, str) {
var value = $(el).val();
value.replace(str, "");
$(el).val(value);
}
$(".minitext > span").html(charactersLeft(".textAreaLarge"));
$("#citation").on("keyup", function(e) {
myTrim(this, "\r");
$(".minitext > span").html(charactersLeft(".textAreaLarge"));
if (!allowType(this)) {
return false;
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="FormRow">
<textarea class="textAreaLarge" rows="20" cols="180" name="citation" id="citation" maxLength="1650"></textarea>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
<strong><div id="sBann" class="minitext"><span></span> characters left.</div></strong>
</div>
With keyup, we can return false to prevent the keystroke event.
Related
What I am trying to do is build the ability to add tagging with a text editor #user and populate a list of users they can select from and it will insert that into the editor. I want to grab all the text before the # when it is typed up to the first space so that I can distinguish if the user is trying to type an email or wanting to add a tag. I know I can just split up the string from # and detect that, but I am having a hard time knowing where to start to get that text to begin with.
Any help would be great.
$(document).on('keyup', '.element', function(e) {
if (e.keyCode == 50) {
//get text here
}
})
Intro
Here is a sample of something that might cover your needs.
However, what I did was indeed of detecting the #, I detected the space.
Once the space was clicked, I went back to find the # .
JSFiddle: https://jsfiddle.net/2uqgorka/35/
JS
let output = document.getElementById("output");
let result = document.getElementById("result");
input.addEventListener('keyup', logKey);
function logKey(e) {
console.log(e);
output.innerHTML += ` ${e.code} + ${e.keyCode}`;
if (e.keyCode == 32) { //Detect a space
let startPos = e.target.selectionStart;
let endPos = e.target.selectionEnd;
//alert(startPos + ", " + endPos);
if(startPos == endPos){
console.log("full input:"+e.target.value);
let textUpToPosition =e.target.value.substring(0,endPos-1);
console.log("textUpToPosition:"+textUpToPosition);
let previousAt = textUpToPosition.lastIndexOf("#");
let previousSpace = textUpToPosition.lastIndexOf(" ");
console.log("previousAt:"+previousAt);
console.log("previousSpace:"+previousSpace);
if(previousSpace < previousAt){
let resultText = textUpToPosition.substring((previousAt));
result.innerHTML = resultText;
}
}
}
}
HTML
<textarea id="input">
#Someone test
</textarea>
<hr>
KeyStrikes<br>
<div id="output">
</div>
<hr>
Result<br>
<div id="result">
</div>
I'm trying to apply Regular Expression Validation to a textbox User Control and it's only working when I enter something at the end of the text in the textbox. And when I type something somewhere in the middle of the text, it's not working.
For Example: Hey Man! (When I type '!' at the end of the text, my Code's working fine)
Hey! Man! (But when I insert '!' somewhere in the middle of the text after the entire text is typed, not working)
Below is my Code:
$("textarea[id$=<%= TxtValue.ClientID %>]").keyup(function () {
var txt = $(this).val();
var regex = new RegExp('[^0-9a-zA-Z-,_.\:\s]+$');
var vldttxt = regex.test(txt);
if (txt.length > 0 && vldttxt === true) {
alert("Error");
}
var noSpclChar = txt.replace(regex, "");
this.value = noSpclChar;
});
Any help would be greatly appreciated! Thanks!
This should work. Your ending $ is what is keeping it from matching anything within the string:
$("textarea[id$=<%= TxtValue.ClientID %>]").keyup(function () {
var txt = $(this).val();
var regex = new RegExp('[^0-9a-zA-Z-,_.\:\s]+');
var vldttxt = regex.test(txt);
if (txt.length > 0 && vldttxt === true) {
alert("Error");
}
var noSpclChar = txt.replace(regex, "");
this.value = noSpclChar;
});
> Most simple code ....Special Characters Validation
function checkForm(theForm) {
var result = /^[a-z0-9\\.;,:'\\s]{1,100}$/i(theForm.data.value);
if (!result) {
alert("No legal characters entered");
}
return !!result;
}
I need to import some formatted html text in a input textarea value
i use jquery
so what's the best way to do it?
i guess first off i need to replace the then strip out the rest (bold, italic, images etc..)
In my first response I didn't see that you wanted to retain line breaks, so here's a better version. It replaces br with an unlikely string %%br%% and then at the end replaces them with new line (\n). So if that string actually appears in the text, it will be replaced by a new line. You can change that to anything you like, just make it something that is unlikely to be encountered in the text.
<script>
function removeMarkup(m) {
var d = document.createElement('div');
d.innerHTML = m;
var c = 0;
// Make brString something that should never appear in the text
// and has no special meaning in a RegExp
var brString = '%%br%%'
var re = new RegExp('\\s*' + brString + '\\s*','g');
function getTextWithReturns(node) {
var tag = node.tagName && node.tagName.toLowerCase();
var nodes = node.childNodes;
var type = node.nodeType;
var s = '';
// Deal with br
if (tag == 'br') {
return brString;
}
if (nodes && nodes.length) {
for (var i=0, iLen=nodes.length; i<iLen; i++) {
s += getTextWithReturns(nodes[i]);
}
} else if (type == 3 || type == 4) {
s += node.nodeValue
}
return s;
}
return reduceWhitespace(getTextWithReturns(d)).replace(re,'\n');
}
function reduceWhitespace(s) {
return s.replace(/^\s*/,'').replace(/\s*$/,'').replace(/\s+/g,' ');
}
</script>
<div id="d0">some text <i>more</i> text
<p>Here is a paragraph with some <b>bold</b> and <i>italic</i> text, plus a <span>span</span> and a line break break break<br> about there.</p>
<p>Here is another paragraph with some <b>bold</b> and <i>italic</i> text, plus plus a <span>span</span> and a line break <br> here.</p>
</div>
<form>
<textarea id="ta0" rows="10" cols="50"></textarea>
<button type="button" onclick="
var ta = document.getElementById('ta0');
var div = document.getElementById('d0');
ta.value = removeMarkup(div.innerHTML);
">Set value</button><input type="reset">
</form>
$("#my_textarea").change(function(){
var cleanText = $("<span />").html(this.value);
this.value = cleanText.text();
});
Example: http://jsfiddle.net/6WbXN/
I have textarea with rows="50" and cols="15".
I want when it's going to wrap the words to simulate enter pressing,because I check when the user goes to new row with keydown and e.which==13 ,but the word wrap prevents me to check this.
edit:
Because I want to try to make something like online editor ,and I dynamicly count the rows like Bespin`s(bespin.mozillalabs.com ,left) rows counting.For this counting I detect when enter is pressed and add new number,but when word wrap is on - it counts wrong ,because when the words are wrapping enter isn't pressed.
Edit 2:
I found a script ,that does what I want ,but how to simulate enter pressing?
<script language="javascript" type="text/javascript">
var ijk = 0;
function txt_ara()
{
//alert("1");
//alert(document.getElementById("email").value.length);
//var ijk = 0;
//var incr = 2;
if(document.getElementById("email").value.length <= 59)
{
if(document.getElementById("email").value.length == 59)
{
document.getElementById("email").value += "\n";
}
}
else
{
var lkm = "";
if(ijk == 0)
{
lkm = parseInt(document.getElementById("email").value.length % 120);
}
else
{
lkm = parseInt(document.getElementById("email").value.length % 60);
}
if(lkm == 0)
{
ijk = 1;
document.getElementById("email").value += "\n";
}
}
}
</script>
<textarea name="email" id="email" class="txtField1" cols="60" rows="26" wrap="off" onkeyup="txt_ara();" onkeydown="txt_ara();"></textarea>
i don't know why you want to do this but you could use 2 "hacks":
1) count the amount of letters and if is == to 1 line of text add a \n
2) use a rich editor as ckeditor in minimal whiteout plugins and add the word wrap option (most of them have something like that)
I would like to ask somebody how i can determine what key was pressed in a textarea....
need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??
till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....
So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)
Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':
$('#ta').keypress(function (evt) {
var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
var fullText = $myTextArea.val(); // here is the full text of the textarea
if (/* do your matching on the full text here */) {
$myTextArea.css('color', 'red'); // changes the textarea font color to red
}
};
I suggest you use the 'onkeyup' event.
$( element ).keyup( function( evt ) {
var keyPressed = evt.keyCode;
//...
});
I have this made like this (plain JS, no JQuery):
function keyDown(e) {
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
if (window.event.srcElement.tagName != 'TEXTAREA') {
var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
}
}
}
document.onkeydown=keyDown;
This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.
2 textareas.
In the first textarea I need to write the words or chars what you want to "watch" in the typing text.
In the second textarea I need to type text, so when I type text, under the textarea need to write what is in the textarea (real time) and highlight the whole word if contains the watched words or chars.
For example:
watched: text locker p
text: lockerroom (need to highlite the whole word because it contains the locker word) or apple (contains the p)
who I can do if a word not start with watched word/char to highlite the whole word?
JavaScript:
var text;
var value;
var myArray;
var found = new Boolean(false);
function getWatchedWords()
{
myArray = new Array();
text = document.getElementById('watched');
value = text.value;
myArray = value.split(" ");
for (var i = 0;i < myArray.length; i++)
{
document.getElementById('writewatched').innerHTML += myArray[i] + "<newline>";
}
}
function checkTypeing()
{
var text2 = document.getElementById('typeing');
var value2 = text2.value;
var last = new Array();
last = value2.split(" ");
if (last[last.length-1] == "")
{
if(found)
{
document.getElementById('writetyped').innerHTML += "</span>";
document.getElementById('writetyped').innerHTML += " ";
}
else
document.getElementById('writetyped').innerHTML += " ";
}
else
check(last[last.length-1]);
}
function check(string)
{
for (var i = 0; i < myArray.length; i++)
{
var occur = string.match(myArray[i]);
if(occur != null && occur.length > 0)
{
if (!found)
{
found = true;
document.getElementById('writetyped').innerHTML += "<span style='color: blue;'>";
}
else
{
found = true;
}
}
else
{
}
}
if(found)
{
document.getElementById('writetyped').innerHTML += string;
}
else
{
document.getElementById('writetyped').innerHTML += string;
}
}
HTML:
<html>
<head>
<title>TextEditor</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src='script.js' type='text/javascript'></script>
</head>
<body>
<div>
<p>Watched words:</p>
<textarea id="watched" onblur=getWatchedWords();>
</textarea>
</div>
<div id="writewatched">
</div>
<div>
<p>Text:</p>
<textarea id="typeing" onkeyup=checkTypeing();>
</textarea>
</div>
<div id="writetyped">
</div>
</body>
</html>