change current TextArea value without assign a new one? - javascript

When I press "A" to add a character to a value of the TextArea, how does the value change?
does the browser do something like this:
texarea.value+="A";
//same as:
texarea.value=texarea.value+"A";
?
I would like to change that value dynamicaly and notify the textarea about the change without assign a new one, because I think that assingment is not very perfomant if the value takes a lot of memory.
Is there a way to do this?

Ok, I solved it:
at first sight this solution seems also not very performant, but it has some big advatages:
for example you could load only a specific part of a very big file from server and dynamically load it if the user scroll through the page.
you can also update the client version of the file representation (synchronized editing)
document.registerElement('text-area', class NicePanel extends HTMLElement {
createdCallback() {
//this.root = this.createShadowRoot();
this.tabIndex = 1;
this.onkeydown = function(e) {
this.monkeydown(e);
}
this.onkeypress = function(e) {
this.monkeypress(e);
}
this.setValue(this.innerHTML);
}
setValue(value) {
var mutablestring = Array.from(value);
this.innerHTML = "";
var l = mutablestring.length;
for (var i = 0; i < l; i++) {
if (mutablestring[i] == '\n') {
var br = document.createElement('br');
br.onclick = this.characterClick;
this.appendChild(br);
} else {
var span = document.createElement('span');
span.onclick = this.characterClick;
span.innerHTML = mutablestring[i];
this.appendChild(span);
}
}
this.cursor = document.createElement('span');
this.cursor.innerHTML = "|";
this.appendChild(this.cursor);
}
getValue() {
var value = "";
var children = this.childNodes;
var that = this;
children.forEach(function(child) {
if (child.nodeName == "BR") {
value += "\n";
return;
}
if (child === that.cursor) return;
value += child.innerHTML;
});
return value;
}
attachedCallback() {}
monkeydown(e) {
var KeyID = event.keyCode;
switch (KeyID) {
case 8:
this.cursor.parentNode.removeChild(this.cursor.previousSibling);
e.preventDefault();
break;
case 46:
this.cursor.parentNode.removeChild(this.cursor.nextSibling);
e.preventDefault();
break;
case 13:
var br = document.createElement('br');
br.onclick = this.characterClick;
this.cursor.before(br);
e.preventDefault();
break;
case 37: //left
this.cursor.parentNode.insertBefore(this.cursor, this.cursor.previousSibling);
break;
case 38: //up
break;
case 39: //right
this.cursor.parentNode.insertBefore(this.cursor, this.cursor.nextSibling.nextSibling);
break;
case 40: //down
break;
default:
break;
}
}
characterClick(e) {
this.parentNode.cursor.parentNode.insertBefore(this.parentNode.cursor, e.target);
}
monkeypress(e) {
var span = document.createElement('span');
span.onclick = this.characterClick;
span.innerHTML = String.fromCharCode(e.which);
this.cursor.parentNode.insertBefore(span, this.cursor);
}
monclick(e) {
var target = e.target; // Clicked element
while (target && target.parentNode !== this) {
target = target.parentNode; // If the clicked element isn't a direct child
if (!target) {
return;
} // If element doesn't exist
}
if (target.tagName === 'SPAN') {
alert(target.id); // Check if the element is a LI
}
}
})
var myta = document.getElementById('myta');
myta.setValue("huhu\nlala");
console.log(myta.getValue());
text-area {
width: 100%;
background: #fff;
display: block;
}
<text-area id="myta" class="text">Hello World
</text-area>

Related

Script does not jump to the next field when the maxlength is reached

This is my script
<script>
var InputContainer = document.getElementsByClassName("InputContainer")[0];
container.onkeyup = function(e) {
var target = e.srcElement || e.target;
var maxLength = parseInt(target.attributes["maxlength"].value, 10);
var myLength = target.value.length;
if (myLength >= maxLength) {
var next = target;
while (next = next.nextElementSibling) {
if (next == null)
break;
if (next.tagName.toLowerCase() === "input") {
next.focus();
break;
}
}
}
// Move to previous field if empty (user pressed backspace)
else if (myLength === 0) {
var previous = target;
while (previous = previous.previousElementSibling) {
if (previous == null)
break;
if (previous.tagName.toLowerCase() === "input") {
previous.focus();
break;
}
}
}
}
</script>
I have also put a around the entire form.
You can find the original webpage at: https://im-here.biz/ContactForm/contact-inc.php
Obviously, I am doing something wrong here.
Ideas?
I can see an error in the console on the above-mentioned URL. By seeing your code there is no container defined. I guess you should be using InputContainer instead of the container variable or change the declaration like this:
<script defer>
// Put your code here
var container = document.getElementsByClassName("InputContainer")[0];
</script>

When I pressing polish letter such as: ó, ł, ą, ż Script moves 3 spaces, when should move only 1 space

When I pressing polish letter such as: ó, ł, ą, ż Script moves 3 spaces, when should move only 1 space.
At this page you can try this script: http://daniel.jajuwa.pl/krzyzowka/index.html
I found the code on the internet, that's why I'm writing here because here is the best chance for a reply;)
Thanks for help :D
(function($){
$.fn.crossword = function(entryData) {
var puzz = {};
puzz.data = entryData;
this.after('<div id="puzzle-clues"><h2>Poziomo</h2><ol id="across"></ol><h2>Pionowo</h2><ol id="down"></ol></div>');
// initialize some variables
var tbl = ['<table id="puzzle">'],
count = 12,
counter = 0,
puzzEl = this,
clues = $('#puzzle-clues'),
clueLiEls,
coords,
entryCount = puzz.data.length,
entries = [],
rows = [],
cols = [],
solved = [],
tabindex,
$actives,
activePosition = 0,
activeClueIndex = 0,
currOri,
targetInput,
mode = 'interacting',
solvedToggle = false,
z = 0;
var puzInit = {
init: function() {
currOri = 'across';
puzz.data.sort(function(a,b) {
return a.position - b.position;
});
puzzEl.delegate('input', 'keyup', function(e){
mode = 'interacting';
switch(e.which) {
case 39:
case 37:
currOri = 'across';
break;
case 38:
case 40:
currOri = 'down';
break;
default:
break;
}
if ( e.keyCode === 9) {
return false;
} else if (
e.keyCode === 37 ||
e.keyCode === 38 ||
e.keyCode === 39 ||
e.keyCode === 40 ||
e.keyCode === 8 ||
e.keyCode === 46 ) {
if (e.keyCode === 8 || e.keyCode === 46) {
currOri === 'across' ? nav.nextPrevNav(e, 37) : nav.nextPrevNav(e, 38);
} else {
nav.nextPrevNav(e);
}
e.preventDefault();
return false;
} else {
console.log('input keyup: '+solvedToggle);
puzInit.checkAnswer(e);
}
e.preventDefault();
return false;
});
// tab navigation handler setup
puzzEl.delegate('input', 'keydown', function(e) {
if ( e.keyCode === 9) {
mode = "setting ui";
if (solvedToggle) solvedToggle = false;
//puzInit.checkAnswer(e)
nav.updateByEntry(e);
} else {
return true;
}
e.preventDefault();
});
// tab navigation handler setup
puzzEl.delegate('input', 'click', function(e) {
mode = "setting ui";
if (solvedToggle) solvedToggle = false;
console.log('input click: '+solvedToggle);
nav.updateByEntry(e);
e.preventDefault();
});
// click/tab clues 'navigation' handler setup
clues.delegate('li', 'click', function(e) {
mode = 'setting ui';
if (!e.keyCode) {
nav.updateByNav(e);
}
e.preventDefault();
});
// highlight the letter in selected 'light' - better ux than making user highlight letter with second action
puzzEl.delegate('#puzzle', 'click', function(e) {
$(e.target).focus();
$(e.target).select();
});
// DELETE FOR BG
puzInit.calcCoords();
// Puzzle clues added to DOM in calcCoords(), so now immediately put mouse focus on first clue
clueLiEls = $('#puzzle-clues li');
//$('#' + currOri + ' li' ).eq(0).addClass('clues-active').focus();
//REMOVED TO STOP FIRST CLUE FROM LOADING ^^^^^
// DELETE FOR BG
puzInit.buildTable();
puzInit.buildEntries();
},
}; // end puzInit object
var nav = {
nextPrevNav: function(e, override) {
var len = $actives.length,
struck = override ? override : e.which,
el = $(e.target),
p = el.parent(),
ps = el.parents(),
selector;
util.getActivePositionFromClassGroup(el);
util.highlightEntry();
util.highlightClue();
$('.current').removeClass('current');
selector = '.position-' + activePosition + ' input';
//console.log('nextPrevNav activePosition & struck: '+ activePosition + ' '+struck);
// move input focus/select to 'next' input
switch(struck) {
case 39:
p
.next()
.find('input')
.addClass('current')
.select();
break;
case 37:
p
.prev()
.find('input')
.addClass('current')
.select();
break;
case 40:
ps
.next('tr')
.find(selector)
.addClass('current')
.select();
break;
case 38:
ps
.prev('tr')
.find(selector)
.addClass('current')
.select();
break;
default:
break;
}
},
updateByNav: function(e) {
var target;
$('.clues-active').removeClass('clues-active');
$('.active').removeClass('active');
$('.current').removeClass('current');
currIndex = 0;
target = e.target;
activePosition = $(e.target).data('position');
util.highlightEntry();
util.highlightClue();
$('.active').eq(0).focus();
$('.active').eq(0).select();
$('.active').eq(0).addClass('current');
// store orientation for 'smart' auto-selecting next input
currOri = $('.clues-active').parent('ol').prop('id');
activeClueIndex = $(clueLiEls).index(e.target);
//console.log('updateByNav() activeClueIndex: '+activeClueIndex);
},
// Sets activePosition var and adds active class to current entry
updateByEntry: function(e, next) {
var classes, next, clue, e1Ori, e2Ori, e1Cell, e2Cell;
if(e.keyCode === 9 || next){
// handle tabbing through problems, which keys off clues and requires different handling
activeClueIndex = activeClueIndex === clueLiEls.length-1 ? 0 : ++activeClueIndex;
$('.clues-active').removeClass('.clues-active');
next = $(clueLiEls[activeClueIndex]);
currOri = next.parent().prop('id');
activePosition = $(next).data('position');
// skips over already-solved problems
util.getSkips(activeClueIndex);
activePosition = $(clueLiEls[activeClueIndex]).data('position');
} else {
activeClueIndex = activeClueIndex === clueLiEls.length-1 ? 0 : ++activeClueIndex;
util.getActivePositionFromClassGroup(e.target);
clue = $(clueLiEls + '[data-position=' + activePosition + ']');
activeClueIndex = $(clueLiEls).index(clue);
currOri = clue.parent().prop('id');
}
util.highlightEntry();
util.highlightClue();
//$actives.eq(0).addClass('current');
//console.log('nav.updateByEntry() reports activePosition as: '+activePosition);
}
}; // end nav object
var util = {
highlightEntry: function() {
// this routine needs to be smarter because it doesn't need to fire every time, only
// when activePosition changes
$actives = $('.active');
$actives.removeClass('active');
$actives = $('.position-' + activePosition + ' input').addClass('active');
$actives.eq(0).focus();
$actives.eq(0).select();
},
highlightClue: function() {
var clue;
$('.clues-active').removeClass('clues-active');
$(clueLiEls + '[data-position=' + activePosition + ']').addClass('clues-active');
if (mode === 'interacting') {
clue = $(clueLiEls + '[data-position=' + activePosition + ']');
activeClueIndex = $(clueLiEls).index(clue);
};
},
getActivePositionFromClassGroup: function(el){
classes = util.getClasses($(el).parent(), 'position');
if(classes.length > 1){
// get orientation for each reported position
e1Ori = $(clueLiEls + '[data-position=' + classes[0].split('-')[1] + ']').parent().prop('id');
e2Ori = $(clueLiEls + '[data-position=' + classes[1].split('-')[1] + ']').parent().prop('id');
// test if clicked input is first in series. If so, and it intersects with
// entry of opposite orientation, switch to select this one instead
e1Cell = $('.position-' + classes[0].split('-')[1] + ' input').index(el);
e2Cell = $('.position-' + classes[1].split('-')[1] + ' input').index(el);
if(mode === "setting ui"){
currOri = e1Cell === 0 ? e1Ori : e2Ori; // change orientation if cell clicked was first in a entry of opposite direction
}
if(e1Ori === currOri){
activePosition = classes[0].split('-')[1];
} else if(e2Ori === currOri){
activePosition = classes[1].split('-')[1];
}
} else {
activePosition = classes[0].split('-')[1];
}
console.log('getActivePositionFromClassGroup activePosition: '+activePosition);
},
checkSolved: function(valToCheck) {
for (var i=0, s=solved.length; i < s; i++) {
if(valToCheck === solved[i]){
return true;
}
}
},
getSkips: function(position) {
if ($(clueLiEls[position]).hasClass('clue-done')){
activeClueIndex = position === clueLiEls.length-1 ? 0 : ++activeClueIndex;
util.getSkips(activeClueIndex);
} else {
return false;
}
}
}; // end util object
puzInit.init();
}
})(jQuery);
the answer is simple don't use it

Javascript - Change certain character color in input

var input = document.getElementById("wordTyped");
var word = document.getElementById("wordGenerated").innerHTML;
window.onload = function() {
window.onkeydown = submit;
function submit(evt) {
if (evt.key == "Enter" && input.value == word) {
input.value = "";
input.style.color = "black";
} else if (evt.key == "Enter" && input.value != word) {
for (i = 0; i < word.length; i++) {
// Below is what I'm querying about
if (input.value[i] != word[i]) {
input.style.color = "red";
}
}
}
}
}
<div id="wordGenerated">illustration</div>
<input id="wordTyped" type="text" />
I don't think what I'm asking is even possible but I want to try changing the color of the input character that does not match with the word
For example,
wordGenerated: illustration
wordTyped: iilustration
The second 'i' in wordTyped should then change its color to red on Enter
I tried doing input.value.style.color[i] = "red" and input.value[i].style.color = "red", but these in return give a TypeError color of undefined.
The code above changed the whole input text color into red.
You just have to wrap your letters in a span element.
NB: the code below is just a prof of concept, I didn't optimize it.
I left optimization part to you.
good luck.
var input = document.getElementById("wordTyped");
var word = document.getElementById("wordGenerated").innerHTML;
window.onload = function() {
window.onkeydown = submit;
function submit(evt) {
var newWord=document.getElementById("wordGenerated");
newWord.innerHTML="";
if (evt.key == "Enter" && input.value == word) {
input.value = "";
input.style.color = "black";
} else if (evt.key == "Enter" && input.value != word) {
for (i = 0; i < input.value.length; i++) {
// Below is what I'm querying about
if (input.value[i] != word[i]) {
var child = document.createElement( "span" );
child.className='colored';
child.innerHTML = input.value[i];
newWord.appendChild( child );
}
else {
var child = document.createElement( "span" );
child.innerHTML = input.value[i];
newWord.appendChild( child );
}
}
}
}
}
.colored {
color: red;
}
<div id="wordGenerated">illustration</div>
<input id="wordTyped" type="text" />

Javascript switch statement?

I have some code like below:
for (var i = 0; i < $scope.Option.length; i++) {
var option = $scope.Option[i].Code;
if (option == "A") {
$scope.aSelected = true;
break;
}
}
for (var i = 0; i < $scope.Option.length; i++) {
var option = $scope.Option[i].Code;
if (option == "B") {
$scope.bSelected = true;
break;
}
}
Is it possible to right this in a switch statement like below:
for (var i = 0; i < $scope.Option.length; i++) {
var option = $scope.Option[i].Code;
switch (option) {
case "A":
$scope.aSelected = true;
break;
case "B":
$scope.bSelected = true;
break;
default:
console.log('unrecognized option');
}
}
Is this actually incorrect in the switch case because the first option may be A which will break out of the loop and then for example if 'B' was the option in a later position of the collection it would never get bSelected = true;
It's correct because the BREAK inside of SWITCH will break out of it, not the whole FOR loop, and therefore it will check for B too.

Only property checked of first radio button works correctly

I am not able to find out why in a function, only if(radioBtn.checked) of the first radio button out of four passes the if. When I log the others, they are still checked when they need to, but the if doesn't seem to work. Here is what I am talking about:
var input = document.getElementsByName("focus");
for(var i = 0; i<input.length; i++) {
input[i].addEventListener("change", function(){
getCheckedRadioValue("focus");
}, false);
}
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName),
i;
this.value = 0;
for (i=0; i < rads.length; i++) {
console.log(rads[3].checked);
if (rads[i].checked){
this.value = rads[i].value;
console.log(this.value);
return rads[i].value
}
return {
value: this.value
}
}
}
document.addEventListener('keydown', function (event) {
if (event.keyCode == 38) {
console.log(value);
switch (value) {
case "car": car.accelerate(); break;
case "boat": boat.accelerate(); break;
case "aircraft": aircraft.accelerate(); break;
case "amphibia": console.log("amphibia"); break;
default: console.log("Nothing is checked!"); break;
}
}
});
Here is everything in jsfiddle.
You return a value after the first iteration of the for-loop. Simply move the default return outside the for-loop like this:
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName), i;
this.value = 0;
for (i = 0; i < rads.length; i++) {
if (rads[i].checked) {
this.value = rads[i].value;
return rads[i].value
}
}
return {
value: this.value
}
}

Categories