Javascript: how to get line/col caret position in textarea? - javascript

I can not find the solution. I've tried to assume that count of \n symbols is the same with lines count, but sometimes this method works incorrectly (e.g. after paste text from clipboard)
i've tried different jQuery plugins, but still unsuccessfully.
any idea?

Why not just do this:
Take the text content only up to selectionStart then make it an array by splitting at eol
p = $('#Form_config').val().substr(0, $('#Form_config')[0].selectionStart).split("\n");
// line is the number of lines
line = p.length;
// col is the length of the last line
col = p[p.length-1].length;

Try to use this:
var pos = getCaretPos(document.formName.textareaName);
function getCaretPos(obj)
{
obj.focus();
if(obj.selectionStart) return obj.selectionStart;//Gecko
else if (document.selection)//IE
{
var sel = document.selection.createRange();
var clone = sel.duplicate();
sel.collapse(true);
clone.moveToElementText(obj);
clone.setEndPoint('EndToEnd', sel);
return clone.text.length;
}
return 0;
}

The descision is not so simple and requieres large amount of javascript code. So, finally i've used CodeMirror Project by Marijn Haverbeke (https://github.com/marijnh/CodeMirror)

Related

remove all Decimals and single numbers from array / string

so my script generates a big blob of "Piano Notes" which are similar to...
var songNotes = "...";
the large Piano notes content
and my problem is between the piano notes which i need [also in the fiddle] there are empty ",," and decimal numbers.. so i cant figure out how to remove the empty
,, and decimals as big as
"1.0416666666642413,0.625,0,g3,1498.9583333333358,,0,c3,1.0416666666642413,0.625,0,c3"
and i want them removed except the the needed words which are
var theRightOnes = "s2,as2,cs3,ds3,fs3,gs3,as3,gs3,cs4,ds4,fs4,cs3,as4,gs4,ds5,a2,cs4,b2,c3,a3,ds4,b3,c4,as3,gs2,e3,c3,c4,cs3,ds3,a4,fs3,gs3,as3,g3,f3,b4,c5,a3,d4,as2,e4,g4,d3,b3,b2,f4,a2,d4,e4,cs5,gs1,e2,c2,c3,cs2,ds2,a3,fs2,gs2,as2,g2,f2,b3,c4,a2,d3,as1,e3,g3,d2,b2,b1,f3,a1,d5,e5";
so can anyone give me a clue on how this can be accomplished?
if anyone needs more info then i am ready oblige to do so..
Regards - Adarsh Hegde
var notesArr = songNotes.split(",");
var len = notesArr.length;
while(len--) {
if(!notesArr[len] || !isNaN(parseInt(notesArr[len], 10))) {
notesArr.splice(len, 1);
}
}
songNotes = notesArr.join(",");
I think you want to remove all the numbers from notes.
You can say like bellow
var notes = songNotes.split(",").filter(function(note){
return isNaN(note);
});
console.log(notes);
You can use Array.filter (see MDN) to weed out unwanted values:
var wantedNotes = songNotes.split(',')
.filter(function (v) {
return isNaN(+v) && v.trim().length
});
jsFiddle
just use regular expression,like this:
var a = "1.0416666666642413,0.625,0,g3,1498.9583333333358,,0,c3,1.0416666666642413,0.625,0,c3";
console.log(a.replace(/\b(\d+(\.\d+)?),+/g,""));

Carriage Returns replacement in IE9

I'm trying to display some data in a <div> and IE9 is not keeping more than one carriage return. This works fine in Chrome, but not IE9 (it only adds the <br/>) Here's the code:
$.get(url,function(xml){
$("record",xml).each(function(){
var profile= $("profile",this).text().replace(/\r\n|\r|\n/g,'~').replace(/~~/g,'<\/p> <p>').replace(/~/g,'<br/>');
profileRpt += profile
});
});
Thought process on this was to normalize, then add <p> for double carriage returns and <br> for the single returns.
I've also tried the simple replacement,
var points= $("points",this).text().replace(/\n\r?/g, '<br />');
and again this worked fine in Chrome, but not in IE9.
Does anyone know of a way I can get this to work in IE9? Thanks!!
UPDATE
So it seems that jQuery is the culprit when used in IE, as it collapses the line breaks prior to any replace function.
Can anyone help with using an alternate (non-jQuery) method of retrieving the data from the xml response as I've done above? One that would preserve the line breaks?
Thanks for your help!
Try this:
function unifyLineFeeds = function(str) {
return str.replace("\r\n", "\n").replace("\r", "\n");
}
You can then use this function to output text as HTML following way:
// `text` var contains text with line ununified line feed characters.
text = unifyLineFeeds(text);
var lines = text.split("\n"),
count = lines.length,
lastIndex = count - 1;
var container = document.getElementById('someContainerToShowFormattedText');
for (var i = 0; i < count; i++) {
container.appendChild(document.createTextNode(lines[i]));
if (i < lastIndex) {
container.appendChild(document.createElement('br'));
}
}
var points = $("points", this).text().replace(/\r+/g, '').replace(/\n/g, '<br>');

How do i get the length of innerHTML (total characters) in JavaScript?

I'm trying to get the length of the characters that I attain from innerHTML and it's kind of come down to last resort, but can't seem to find a more efficient way as the data is inside a slider that I'm trying to use to get the lower value and higher value.
var lvalue=document.getElementById("lval").innerHTML;
then I'm spiting the string in the spaces:
var larr=lvalue.split(" ");
The innerHTML value is something like this "2413dsk 134dfa134".
And when i use larr[0].length, I get 1 when I need 7. Is there a solution?
I think it would go something like this:
var lvalue = document.getElementById("lval").innerHTML;
var larr = lvalue.split(' ');
var len = 0;
// For each iterates over the index of arrays
for(var i in larr) {
len += larr[ i ].length // Acummulate the length of all the strings
}
Or alternatively you could count the spaces first and then substract it from the total length.
// Some people argue about extending the native objects
// but in this case I think this method is a natural fit.
String.prototype.count = function( character ) {
var l = 0;
// `this` refers to the string itself
for(var c in this) n = this[ c ] === character ? ++n : n;
return n;
}
An then use it like so:
var lvalue = document.getElementById("lval").innerHTML;
// Subtract total length minus the number of spaces
var len = lvalue.length - lvalue.count(' ');
This might be caused by a preceding or leading space.
Try trimming the extra spaces :
var lvalue=document.getElementById("lval").innerHTML.replace(/^\s+/gi,'').replace(/\s+$/gi,'');
var larr=lvalue.split(" ");
I didn't see any problem with your code. I run a test here: http://desdegdl.com/lval.html
Probably, you have one or more spaces at the begining of lval's inner HTML.
If there is someone like me that doesn't want to use JQuery, here is a example in javascript (only)...
The files
The html file...
<!-- start body -->
<body>
<!-- start section -->
<section id="bar"></section>
<!-- end section -->
</body>
<!-- end body -->
The javascript file...
/* start - wut element do ya wanna get? */
foo = document.getElementById('bar');
/* end - wut element do ya wanna get? */
/* start function */
function isEmpty(){
if (foo.innerHTML.length === 0) {
/* your code here */
}
}
/* end function */
What I did
In the HTML
Quite simple, I just created a section and assigned an ID on it. This ID will be used to call her in our javascript.
In the JavaScript
In the var fooI I called the section whose I gave an ID.
After it I created a function that "do something" if the length of a element is equal zero.
Considerations
It works, but if you have a space or a line break the code will not consider it as "empty"...

Having a <Textarea> with a max buffer

I have seen plenty of code snippets to force a <Textarea> to have only X number of characters and then not allow anymore. What I am in need of is a <Textarea> where you can specify how many characters I can have at one time at most. Almost like a max buffer size. Think of it like a rolling log file. I want to always show the last/newest X number of characters.
Simpler the solution the better. I am not a web expert so the more complicated it gets the more greek it looks to me. :)
I am already using jQuery so a solution with that should be ok.
try this:
<textarea id="yourTextArea" data-maxchars="1000"></textarea>
var textarea = document.getElementById('yourTextArea');
var taChanged = function(e){
var ta = e.target;
var maxChars = ta.getAttribute('data-maxchars');
if(ta.value.length > maxChars){
ta.value = ta.value.substr(0,maxChars);
}
}
textarea.addEventListener('change', taChanged, 1);
for the last chars:
ta.value = ta.value.substr(ta.value.length - 1000);
And jQuery implementation:
$('#text').keyup(function() {
var max = $(this).data('maxchars'),
len = $(this).val().length;
len > max && $(this).val(function() {
return $(this).val().substr(len - max);
});
});
http://jsfiddle.net/WsnSk/
No code, I can't even spell JavaScript, but basically as you're about to add new text, check the length of the existing text. If the old text plus the new text is too long, trim off the beginning of the old text (likely at a newline or whatever). Rinse and repeat.
Here is the working code on Fiddle. It uses Jquery to make it simple.
<textarea id="txtArea"></textarea>
var size = 5;
$('#txtArea').change(function(){
var strValue = $('#txtArea').val();
strValue = strValue.split("").reverse().join("").substring(0, size).split("").reverse().join("");
alert(strValue);
});

parse a textarea in substrings based on line breaks in Javascript

I have a text area that I need to parse. Each new line needs to be pulled out and an operation needs to be performed on it. After the operation is done the operation needs to be run on the next line. This is what I have at the moment. I know the indexOf search won't work because it's searching character by character.
function convertLines()
{
trueinput = document.getElementById(8).value; //get users input
length = trueinput.length; //getting the length of the user input
newinput=trueinput; //I know this looks silly but I'm using all of this later
userinput=newinput;
multiplelines=false; //this is a check to see if I should use the if statement later
for (var i = 0; i < length; i++) //loop threw each char in user input
{
teste=newinput.charAt(i); //gets the char at position i
if (teste.indexOf("<br />") != -1) //checks if the char is the same
{
//line break is found parse it out and run operation on it
userinput = newinput.substring(0,i+1);
submitinput(userinput);
newinput=newinput.substring(i+1);
multiplelines=true;
}
}
if (multiplelines==false)
submitinput(userinput);
}
So for the most part it is taking the userinput. If it has multiply lines it will run threw each line and seperatly and run submitinput. If you guys can help me I'd be eternally thankful. If you have any questions please ask
Line breaks within the value of a textarea are represented by line break characters (\r\n in most browsers, \n in IE and Opera) rather than an HTML <br> element, so you can get the individual lines by normalizing the line breaks to \n and then calling the split() method on the textarea's value. Here is a utility function that calls a function for every line of a textarea value:
function actOnEachLine(textarea, func) {
var lines = textarea.value.replace(/\r\n/g, "\n").split("\n");
var newLines, i;
// Use the map() method of Array where available
if (typeof lines.map != "undefined") {
newLines = lines.map(func);
} else {
newLines = [];
i = lines.length;
while (i--) {
newLines[i] = func(lines[i]);
}
}
textarea.value = newLines.join("\r\n");
}
var textarea = document.getElementById("your_textarea");
actOnEachLine(textarea, function(line) {
return "[START]" + line + "[END]";
});
If user is using enter key to go to next line in your text-area you can write,
var textAreaString = textarea.value;
textAreaString = textAreaString.replace(/\n\r/g,"<br />");
textAreaString = textAreaString.replace(/\n/g,"<br />");
textarea.value = textAreaString;
to simplify the answers, here is another approach..
var texta = document.getElementById('w3review');
function conv (el_id, dest_id){
var dest = document.getElementById(dest_id),
texta = document.getElementById(el_id),
val = texta.value.replace(/\n\r/g,"<br />").replace(/\n/g,"<br />");
dest.innerHTML = val;
}
<textarea id="targetted_textarea" rows="6" cols="50">
At https://www.a2z-eco-sys.com you will get more than what you need for your website, with less cost:
1) Advanced CMS (built on top of Wagtail-cms).
2) Multi-site management made easy.
3) Collectionized Media and file assets.
4) ...etc, to know more, visit: https://www.a2z-eco-sys.com
</textarea>
<button onclick="conv('targetted_textarea','destination')" id="convert">Convert</button>
<div id="destination">Had not been fetched yet click convert to fetch ..!</div>

Categories

Resources