output all characters and recognize end of js-function - javascript

i have put together the undermentioned script. it wont output the last character of the last source. i am not very well concerned with js and that is why i ask you. can anyone give me a clue?
function jtype(source, step){
var str = source, i = 0, isTag, text, all = "", ii = 0, totallength = 0;
for(ii = 1; ii < step; ii++){
all = all + $("#source-" + ii).val();
}
(function type() {
text = str.slice(0, ++i);
if (text === str) return;
$(".steps").html(all + text);
var char = text.slice(-1);
if( char === '<' ) isTag = true;
if( char === '>' ) isTag = false;
if (isTag) return type();
setTimeout(type, 20);
}());
}
this is an example-data-source:
<input type="hidden" class="sources" id="source-1" value="Gesetzliche Zinsen gebühren kraft Gesetzes. ">
<input type="hidden" class="sources" id="source-2" value="Der gesetzliche Zinssatz beträgt nach <a href="#" onclick="dofadein('#norm330')">§ 1000 Abs 1 ABGB</a> 4 Prozentpunkte pro Jahr. ">
<input type="hidden" class="sources" id="source-3" value="Gesetzliche Zinsen sind insb die sog Verzugszinsen nach <a href="#" onclick="dofadein('#norm430')">§ 1333 ABGB</a>.">
in this example it wont output the dot at the end of #source-3.
when i make an alert(source) right in the function jtype() the dot is NOT missing.
the other thing i want to know is. how can i determine the end of the output. i mean: how can i determine if the cycling is finished and the last character has been output?
thank you very much for your help and please excuse my bad english.

The problem seems to be that when the text === str you return before updating the element so the last character never gets inserted
Change:
if (text === str) return;
$(".steps").html(all + text);
To:
// update element before ending
$(".steps").html(all + text);
if (text === str) return;
DEMO

Related

How to check letter by letter using addEventListener 'keydown'?

I'm trying to check if is true or false the letter I typed.
for exemplo, I have one String that I caught from a array doing join(' '):
"problem test javascript css pc"
My current code:
document.addEventListener('keydown', (event) => {
let count = 0
let charlist = "problem test javascript css pc"
for(let i = 0; i < charlist.length; i++){
if(charlist[i] === event.key){
count++
console.log(count)
}
}
})
When I type "s" is counting 2, and when I type "t" is counting 3, there is no sequence..
What I need is check just the first letter "p" and count 1 return true, type letter "r" count 1 return true
how can I test this ?
A different approach than #Kinglish's answer compares the string's current character using the current count.
let count = 0
document.addEventListener('keydown', (event) => {
let mystring = "problem test javascript css pc"
for(let i = count; i < mystring.length; i++){
if(event.key == mystring.charAt(i)){
console.log('correct character')
count++
break;
}
if (event.key != mystring.charAt(count+1)) {
console.log('wrong character')
break;
}
}
})
<div>problem test javascript css pc</div>
<input style="margin-top: 10px;" class="typebox" placeholder="type here..."></div>
Here's an example you can follow. First you store the phrase as an array, and for every keydown, compare the event.key with the letter that matches the counter index of the phrase array. For each correctly keyed letter, you advance your counter. Look through this code to get an idea of how it works
let keycounter = 0,
correct = 0,
wrong = 0;
let response = document.querySelector('.response')
let completed = document.querySelector('.completed')
document.addEventListener('keydown', (event) => {
let count = 0
let charlist = "problem test javascript css pc";
if (charlist.split('')[keycounter] === event.key) {
completed.innerHTML += event.key
correct++;
keycounter++
response.innerHTML = event.key + ' was correct';
} else {
wrong++;
response.innerHTML = event.key + ' was wrong';
}
response.innerText += ' - ' + correct + ' right/' + wrong + ' wrong so far'
if (correct === charlist.split('').length) response.innerText += +"<br> FINISHED";
})
.completed:empty, .response:empty{
display:none;
}
.completed, .response{
margin:5px 0;
padding:5px;
background:#f0f0f0;
}
.response{
color:#666;
}
<p>Click in this area and type in this phrase <strong>problem test javascript css pc</strong></p>
<div class='completed'></div>
<div class='response'></div>

Pure Javascript - get beginning position of current line in a multiline textarea

I'm looking for a pure javascript answer as that reflects my projects scope. jQuery answers will not be marked correct, but are welcomed for future question seekers. Side note: I am also not interested in third party libraries.
I'm trying to get the first position (0) of the current line (current is based of selectionStart the chance the user selects more than 1 line) in a multiline textarea, but translate that to caret index.
What have I tried? Nothing pretty:
for ( i = 0; i < this.selectionStart; i++ ) {
if (this.value.substr(i,1).match(/\r?\n|\r/)) {
lineStartIndx = i + 1
}
}
This is proving to be costly when iterating textareas with huge amounts of lines. My personal usage of this will not be executed every keydown, however, I just used it as an example. Are there any better methods, built in or otherwise to emulate this outcome?
My full example:
var input = document.getElementById("ta");
var output = document.getElementById("output");
let pattern = /\r?\n|\r/;
var lineNum, lineStartIndx;
input.addEventListener("keydown", function(e) {
taHandler(this);
})
input.addEventListener("click", function(e) {
taHandler(this);
})
function taHandler(elem) {
lineNum = getLineNumForSelection(elem);
let caretPos = elem.selectionStart;
lineStartIndx = 0;
for ( i = 0; i < caretPos; i++ ) {
if (elem.value.substr(i,1).match(pattern)) {
lineStartIndx = i + 1
}
}
output.innerHTML = "Selection Start: " + caretPos + " Selection End: " + elem.selectionEnd +
" <br> Line Number: " + lineNum.start +
"<br>Line Start Position: " + lineStartIndx;
}
function getLineNumForSelection(sel) {
return {
'start' : sel.value.substr(0, sel.selectionStart).split(pattern).length,
'end' : sel.value.substr(0,sel.selectionEnd).split(pattern).length
};
}
<textarea id="ta" rows="5" cols="50">
Line one
Line two
Line three
Line four
</textarea>
<hr>
<div id="output"></div>
The method in my copy of the snippet splits the content into lines and uses the .length property instead of a loop so it looks "prettier" but according to time complexity of javascript's .length may not be any faster since there is nothing in the spec that prevents slow browser implementation.
Two side notes about the code, I'd use lineStartIndex, not lineStartIndx without the e. Since lineNum is an array, I'd use lineNumArray or selLineNums or something that is more obvious since variables ending in num are generally integers.
var input = document.getElementById("ta");
var output = document.getElementById("output");
let pattern = /\r?\n|\r/;
var lineNum, lineStartIndx;
input.addEventListener("keydown", function(e) {
taHandler(this);
})
input.addEventListener("click", function(e) {
taHandler(this);
})
function taHandler(elem) {
lineNum = getLineNumForSelection(elem);
let caretPos = elem.selectionStart;
lineStartIndx = 0;
// begin modified code
let lines = elem.value.split(pattern),
lineIndex = 0;
while ( (lineIndex + 1 ) < lineNum.start ) {
lineStartIndx += parseInt( lines[lineIndex].length ) + 1;
lineIndex++;
}
// end modified code
// begin replaced code
for ( i = 0; i < caretPos; i++ ) {
if (elem.value.substr(i,1).match(pattern)) {
lineStartIndx = i + 1
}
}
// end replaced code
output.innerHTML = "Selection Start: " + caretPos + " Selection End: " + elem.selectionEnd +
" <br> Line Number: " + lineNum.start +
"<br>Line Start Position: " + lineStartIndx;
}
function getLineNumForSelection(sel) {
return {
'start' : sel.value.substr(0, sel.selectionStart).split(pattern).length,
'end' : sel.value.substr(0,sel.selectionEnd).split(pattern).length
};
}
<textarea id="ta" rows="5" cols="50">
Line one
Line two
Line three
Line four
</textarea>
<hr>
<div id="output"></div>

Adding a space after 4 chars in an input [duplicate]

I'm really new in JavaScript and I would like to add to my input text, space insertion for IBAN account registering.
<input type="text" name="iban" onkeyup="if(this.value.length > 34){this.value=this.value.substr(0, 34);}" />
There is my input field; could someone tell me how I can do this?
The existing answers are relatively long, and they look like over-kill. Plus they don't work completely (for instance, one issue is that you can't edit previous characters).
For those interested, according to Wikipedia:
Permitted IBAN characters are the digits 0 to 9 and the 26 upper-case Latin alphabetic characters A to Z.
Here is a relatively short version that is similar to the existing answers:
document.getElementById('iban').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
});
<label for="iban">iban</label>
<input id="iban" type="text" name="iban" />
As stated above, the caveat is that you can't go back and edit previous characters. If you want to fix this, you would need to retrieve the caret's current position by initially accessing the selectionEnd property and then setting the caret's position after the regex formatting has been applied.
document.getElementById('iban').addEventListener('input', function (e) {
var target = e.target, position = target.selectionEnd, length = target.value.length;
target.value = target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});
<label for="iban">iban</label>
<input id="iban" type="text" name="iban" />
You will notice that there is a slight issue when the character after the caret is a space (because the space wasn't accounted for when initially retrieving the caret's position to begin with). To fix this, the position is manually incremented if the succeeding character is a space (assuming a space was actually added - which is determined by comparing the length before and after replacing the characters).
Using plain-JavaScript, I'd suggest:
function space(el, after) {
// defaults to a space after 4 characters:
after = after || 4;
/* removes all characters in the value that aren't a number,
or in the range from A to Z (uppercase): */
var v = el.value.replace(/[^\dA-Z]/g, ''),
/* creating the regular expression, to allow for the 'after' variable
to be used/changed: */
reg = new RegExp(".{" + after + "}","g")
el.value = v.replace(reg, function (a, b, c) {
return a + ' ';
});
}
var el = document.getElementById('iban');
el.addEventListener('keyup', function () {
space(this, 4);
});
JS Fiddle demo.
Somewhat belatedly, my rewrite of the above to handle strings, rather than DOM nodes:
function space(str, after) {
if (!str) {
return false;
}
after = after || 4;
var v = str.replace(/[^\dA-Z]/g, ''),
reg = new RegExp(".{" + after + "}", "g");
return v.replace(reg, function (a) {
return a + ' ';
});
}
var el = document.getElementById('iban');
el.addEventListener('keyup', function () {
this.value = space(this.value, 4);
});
JS Fiddle demo.
References:
addEventListener().
JavaScript regular expressions.
I wrote a simple function extending David's function to handle the last space. Also you can specify the separator.
function spacify(str, after, c) {
if (!str) {
return false;
}
after = after || 4;
c = c || " ";
var v = str.replace(/[^\dA-Z]/g, ''),
reg = new RegExp(".{" + after + "}", "g");
return v.replace(reg, function (a) {
return a + c;
}).replace(/[^0-9]+$/, "");
}
console.log(spacify("123123123131",4," "))
console.log(spacify("12312312313",4,"-"))
The code from Josh Crozie is really nice, but not complete.
Two issues with it;
If the caret is not at the end but e.g. at the before last position and the user starts typing, sometimes the caret doesn't stay at the before last position
Another issue is with Android 7+ devices. Those devices update the caret position slightly later, that means it needs a setTimeout() before reading the caret location
The code below is based on the code of Josh Crozie, now with the two issues mentioned above fixed and a little more verbose for readability purpose:
var isAndroid = navigator.userAgent.indexOf("ndroid") > -1;
var element = document.getElementById('iban');
element.addEventListener('input', function () {
if (isAndroid) {
// For android 7+ the update of the cursor location is a little bit behind, hence the little delay.
setTimeout(reformatInputField);
return;
}
reformatInputField();
});
function reformatInputField() {
function format(value) {
return value.replace(/[^\dA-Z]/gi, '')
.toUpperCase()
.replace(/(.{4})/g, '$1 ')
.trim();
}
function countSpaces(text) {
var spaces = text.match(/(\s+)/g);
return spaces ? spaces.length : 0;
}
var position = element.selectionEnd;
var previousValue = element.value;
element.value = format(element.value);
if (position !== element.value.length) {
var beforeCaret = previousValue.substr(0, position);
var countPrevious = countSpaces(beforeCaret);
var countCurrent = countSpaces(format(beforeCaret));
element.selectionEnd = position + (countCurrent - countPrevious);
}
}
<label for="iban">iban</label>
<input id="iban" type="text" name="iban" size="35" />
You have to capture each group of 4 digits and then put a space between each group.
$('input').blur(function () {
//Replace each group 4 digits with a group plus a space
var reformat = this.value.replace(/(\d{4})/g, function(match){
return match + " ";
});
this.value = reformat;
})
And this one updates the element while typing
//Keys pressed 0 times
var downed = 0;
$('#test').keydown(function (g) {
if(g.code.match("^Digit")){
downed++;
console.log(g)
}
if(downed == 1){
var reformat = this.value.replace(/(\d{4}\s*)/g, function(match){
//Strip spaces
if(match.match(/\s/)){return match;}
return match + " ";
});
console.log(reformat);
this.value = reformat;
//Start recount
downed = 0;
}
});
Check out the fiddle
for thousands on angular 4 in a pipe
integer = integer.replace(/[^\dA-Z]/g, '').replace(/(.{3})/g, '$1.').trim();
I need the same but for BVR/BVR+ swiss payment form.
So what I need is add a space every 5 chars but from the end of the string.
Example : "52 86571 22001 00000 10520 15992" or sometimes shorter like "843 14293 10520 15992".
So, here is the solution by reversing the string before and after adding spaces if rev=1.
function space(str, stp, rev) {
if (!str) {
return false;
}
if (rev == 1) {
str = str.split('').reverse().join('');
}
if(stp > 0) {
var v = str.replace(/[^\dA-Z]/g, ''),
reg = new RegExp(".{" + stp + "}", "g");
str = v.replace(reg, function (a) {
return a + ' ';
});
}
if (rev == 1) {
str = str.split('').reverse().join('');
}
return str;
}
Use :
var refTxt = space(refNum, 5, 1);
EDIT : PHP version added
function space($str=false, $stp=0, $rev= false) {
if(!$str)
return false;
if($rev)
return trim(strrev(chunk_split(strrev($str), $stp, ' ')));
else
return trim(chunk_split($str, $stp, ' '));
}
document.getElementById('iban').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
});
<label for="iban">iban</label>
<input id="iban" type="text" name="iban" />
This is the shortest version using JQuery on input with type number or tel:
$('input[type=number], input[type=tel]').on('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
});
You can also change the 4 to any other character limit you want.
onChangeText={number => {
const data =
number.length % 5 !== 4
? number
.replace(/[^\dA-Z]/g, '')
.replace(/(.{4})/g, '$1-')
.trim()
: number;
this.setState({
...this.state,
card: {...this.state.card, number: data},
});
}}
If you are trying to use for text input to adjust with credit card then this method will help you solve the backspace problem too
To Add space after 4 Digits
Useful to validate IBAN Number
document.getElementById('IBAN').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
});
<label for="IBAN">IBAN</label>
<input id="IBAN" maxlength="14" type="text" name="IBAN" />

Simple dom inspector script counts incorrectly child nodes

I have simple js function that returns me dom path to clicked element. However sometimes some element(usually the one i have clicked) counts twice
so if i have following code
<ul>
<li><a href ='#'>Some link</a></li>
</ul>
the output could be like ul:nth-child(1) > li:nth-child(1) > a:nth-child(2)
while a should be 1 child.
Here is the code of function
var getDomPath;
getDomPath = function(el) {
var count, element, nth, path, selector, sib;
element = el;
if (!(el instanceof Element)) {
return;
}
path = [];
while (el.nodeType === Node.ELEMENT_NODE && el.id !== "jobs") {
selector = el.nodeName.toLowerCase();
if (el.id) {
selector += "#" + el.id;
} else if (el.className) {
selector += "." + el.className;
} else {
sib = el;
nth = 1;
count = 1;
while (sib.nodeType === Node.ELEMENT_NODE && (sib = sib.previousSibling) && $(el).prev().prop('tagName') !== "STYLE" && $(el).prev().prop('tagName') !== null) {
count += $(el).prevAll().size();
}
selector += ":nth-child(" + count + ")";
}
path.unshift(selector);
el = el.parentNode;
}
return path.join(" > ");
};
Code was converted from coffee to javascript, so might looks a little bad
here is html that im trying to get path to
<td width="50%"><strong>Leveringssadresse</strong>
<br>
Hans Andersen
<br>
Andevej 123
<br>
1234 Andeby
<br>
Denmark
<br>
Telefon: 31122345
<br>
Mobiltelefon: 12232345
<br>
mail#gmail.com
<br>
</td>
Here when i click on a element i expect it to be nth-child(8), but somehow i'm getting it 17(16 + 1 as increment by 1 in my code)
Just noticed you use jQuery.
Why not simplify it to just
function getDomPath(element){
var path = $(element).parents().andSelf().map(function(){
var index = $(this).index() + 1;
return this.nodeName.toLowerCase() + ':nth-child('+ index +')';
}).get();
return path.join(' > ');
}
Demo at http://jsfiddle.net/BEUrn/3/
The problem is with this line:
while (sib.nodeType === Node.ELEMENT_NODE && (sib = sib.previousSibling) && $(el).prev().prop('tagName') !== "STYLE" && $(el).prev().prop('tagName') !== null) {
I have read this line multiple times, and I can't work out what you're trying to do.
Your code says:
make sure that the currently examined node is an element
set the currently examined node to be its previous sibling
check that the element before the original node has a tag name that isn't STYLE
I have no idea what that sequence of steps is intended to be, but if the final condition passes, it will calculate n * (x + 1) + 1, where n is the number of preceding element siblings and x is the number of immediately preceding element siblings without intervening text nodes.
The next line is this:
count += $(el).prevAll().size();
This, surely, should only be run once, with the conditional not necessary at all.
count = $(el).prevAll().length + 1;
jsFiddle with working code.

word limits on multiple text areas

I am creating a website with four textarea forms. Each form has a word limit.
textarea1: 250 word limit
textarea2: 500 word limit
textarea3: 500 word limit
textarea4: 250 word limit
I have tried using existing examples that I have found when trying to fix this problem but nothing seems to work.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var maxwords = 250;
//
function check_length(obj, cnt, rem)
{
var ary = obj.value.split(" "); // doubled spaces will throw this off
var len = ary.length;
cnt.innerHTML = len;
rem.innerHTML = maxwords - len;
if (len > maxwords) {
alert("Message in '" + obj.name + "' limited to " + maxwords + " words.");
ary = ary.slice(0,maxwords-1);
obj.value = ary.join(" "); // truncate additional words
cnt.innerHTML = maxwords;
rem.innerHTML = 0;
return false;
}
return true;
}
</script>
HTML
<textarea name="Message 1" onkeypress="
return check_length(this,
document.getElementById('count1'),
document.getElementById('remaining1'));"></textarea>
Word count: <span id="count1">0</span>
Words remaining: <span id="remaining1">250</span>
<textarea name="Message 2" onkeypress="
return check_length(this,
document.getElementById('count2'),
document.getElementById('remaining2'));"></textarea>
Word count: <span id="count2">0</span>
Words remaining: <span id="remaining2">500</span>
Does anyone know a solution to this problem?
Thanks in advance,
Tom
Add an extra parameter to your function, and send it the maxWords from each function call:
function check_length(obj, cnt, rem, maxwords)
{
//... rest of the function would stay the same
and when you call it, include the max words
<textarea name="Message 2" onkeypress="
return check_length(this,
document.getElementById('count2'),
document.getElementById('remaining2'), 250);"></textarea>
Word count: <span id="count2">0</span>
Words remaining: <span id="remaining2">500</span>
To remove the words remaining,
function check_length(obj, cnt, maxwords)
{
var ary = obj.value.split(" "); // doubled spaces will throw this off
var len = ary.length;
cnt.innerHTML = len;
if (len > maxwords) {
alert("Message in '" + obj.name + "' limited to " + maxwords + " words.");
ary = ary.slice(0,maxwords-1);
obj.value = ary.join(" "); // truncate additional words
cnt.innerHTML = maxwords;
return false;
}
return true;
}
and in your HTML,
<textarea name="Message 1" onkeypress="
return check_length(this,
document.getElementById('count1'),250);"></textarea>
Word count: <span id="count1">0</span>
insert a class attribute for those textareas, (like class='area250', class='area500' and so on) then include an if statement in the function
function check_length(obj, cnt, rem)
{
if(window.event.srcElement.getAttribute('class')=='area250')
maxwords=250;
else if(window.event.srcElement.getAttribute('class')=='area500')
maxwords=500;
else .......................................
}
The problem with your function is that you're always checking the amount of words inserted against maxwords variable (which is set to 250 words as the first textarea limit)
so a better attempt is to pass an extra parameter to the function with the original limit (different for each textarea)

Categories

Resources