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" />
Related
I want to be able to perform validation based on how many characters were entered by the user - I want there to be a minimum of 7 characters. (The maximum value is set using an HTML attribute) - I have tried the following:
v3 = document.getElementById("npo-registration-number");
flag3 = true;
if (val >= 3 || val == 0) {
if (v3.value == "") {
v3.style.borderColor = "red";
flag3 = false;
}
else if (v3.value.length === 7){
v3.style.borderColor = "green";
flag3 = true;
}
}
The above works to an extent. The input fields border colour will only show green if 7 characters are inputted. However, if i delete characters from that point onwards, the border remains green. Any help on the matter is appreciated.
I'm not entirely sure about what you want; is this close to what you are looking for?
You probably did this and didn't include it in your snippet, but we need this to run each time the form is edited. We add an event listener to the input.
const input = document.getElementById('npo-registration-number');
input.addEventListener('input', () => {
// set the border to red if the value is < 7 characters
if (input.value.length < 7) {
input.style.borderColor = 'red';
return;
}
// otherwise, set it to green
input.style.borderColor = 'green';
});
This fixes an issue: you do not set the color of the border to red unless the value of the form is an empty string. Rather, we want the border to be red whenever the input length goes below seven.
It's because of your condition
if (v3.value == "") {
v3.style.borderColor = "red";
flag3 = false;
}
When you start deleting characters in input, your input is not becoming red again because It's red only when there are no characters and it change to green after 7 characters inputed.
You need to capture the input event so js can evaluate and update.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
const ev3 = document.getElementById("npo-registration-number");
let flag3 = true;
ev3.addEventListener('input', (e) => {
const val = e.target.value;
if (val.length === 7){
ev3.style.borderColor = "green";
flag3 = true;
}
else {
ev3.style.borderColor = "red";
flag3 = true;
}
});
input {
outline: 0;
border: 1px solid;
}
<input id="npo-registration-number" type='text'>
You can just use button that will run this function for it, like send or post buttons(many sites use this method).
function click(){
v3 = document.getElementById("npo-registration-number");
flag3 = true;
if (val >= 3 || val == 0) {
if (v3.value == "") {
v3.style.borderColor = "red";
flag3 = false;
}
else if (v3.value.length === 7){
v3.style.borderColor = "green";
flag3 = true;
}
}
}
Try this please
v3 = document.getElementById("npo-registration-number");
flag3 = true;
if (v3.value == "") {
v3.style.borderColor = "red";
flag3 = false;
} else {
if (v3.value.length < 7){
v3.style.borderColor = "red";
flag3 = false;
}
else {
v3.style.borderColor = "green";
flag3 = true;
}
}
I was trying many solutions but none worked.
The problem is where I put the comment.
I trying to do a game which I can change a color of boxes using arrows.
var p = 0;
var d0 = document.getElementById('p1').getAttribute('value');
var d1 = document.getElementById('p2').getAttribute('value');
var arraj = [];
arraj.push(d0, d1);
function change() {
for (var i = 0; i < arraj.length; i++) {
if (arraj[i] == p) {
// and here is the problem
arraj[i].style.backgroundColor = "red";
}
}
}
document.onkeydown = check;
function check(e) {
e = e || window.event;
if (e.keyCode == '37') {
// left
} else if (e.keyCode == '39') {
p++;
change();
// right
}
}
and HTML
<div class='g' id='p1' value="0">bla</div>
<div class='g' id='p2' value="1">bla</div>
This should fix it:
var p = 0;
var d0 = document.getElementById('p1'); // Remove 'getAttribute('value')' here
var d1 = document.getElementById('p2'); // Remove 'getAttribute('value')' here
var arraj = [];
arraj.push(d0, d1);
function change() {
for (var i = 0; i < arraj.length; i++) {
if (arraj[i].getAttribute('value') == p) { // Check for the attribute equality here
arraj[i].style.backgroundColor = "red";
}
}
}
document.onkeydown = check;
function check(e) {
e = e || window.event;
if (e.keyCode == '37') {
// left
} else if (e.keyCode == '39') {
p++;
change();
// right
}
}
Basically the main issue that you're trying to set background color on element's value attribute and not the element itself.
I am trying this very simple code to realize a TicTacToe in plain Javascript:
function inizializza()
{
var x = document.querySelectorAll(".riga div");
var i;
for (i = 0; i < x.length; i++) {
document.querySelectorAll(".riga div")[i].addEventListener("click",
cambia);
}
}
var segno = "X";
function cambia()
{
if (this.innerHTML != "")
{
alert("ERRORE!")
}
else
{
this.innerHTML = segno;
if (segno == "X")
segno = "O";
else
segno = "X";
}
}
Function inizializza() is called on body load.
When you click on a .riga div (a cell in my game table), the event click should change the text displayed in the cell: X or O. But this is not working, because I can't use "this" kewyword to retrieve clicked object properties.
How can I do it?
Thanks a lot!
Giancarlo
you can use closures here
check the following snippet
window.onload = function() {
inizializza();
}
function inizializza() {
var x = document.querySelectorAll(".riga div");
var i;
for (i = 0; i < x.length; i++) {
document.querySelectorAll(".riga div")[i].addEventListener("click",function(event){
cambia(this);
});
}
}
var segno = "X";
function cambia(obj) {
if (obj.innerHTML == "") {
alert("ERRORE!")
} else {
obj.innerHTML = segno;
if (segno == "X")
segno = "O";
else
segno = "X";
}
}
<div class="riga">
<div>1</div>
<div>2</div>
<div>3</div>
<div>X</div>
</div>
Hope it helps
You can use the event object passed as the first argument of the click event.
event.target will work for most of the browser and event.srcElement works with few old microsoft browsers.
function inizializza()
{
var x = document.querySelectorAll(".riga div");
console.log(x);
var i;
for (i = 0; i < x.length; i++) {
document.querySelectorAll(".riga div")[i].addEventListener("click",
cambia);
}
}
var segno = "X";
function cambia(event)
{
var element = event.target || event.srcElement;
if (target.innerHTML !== "")
{
alert("ERRORE!")
}
else
{
this.innerHTML = segno;
if (segno == "X")
segno = "O";
else
segno = "X";
}
}
Working example : https://plnkr.co/edit/NaTwU7XmmU9sLgNiFrjO?p=preview
Saw this post about getting the html from the selected/higlighted text. And it does work in getting the html.
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
alert(getSelectionHtml());
But, suppose there's this html:
<p>I am <span style="color:green;">green</span> and I have <span style="background-color:yellow;">yellow background<span>.</p>
Now if the word green is highlighted, then it will just get the word
"green"
even if there's <span> tag surrounded. But if selected more character than the word green (say the space before or after the word green like this " green"), it will get the html tag too, such as:
<span style="color:green;">green</span>
Please check out the demo
Is it possible to get the html even if only the word "green" is highlighted?
Eventually what I want to achieve is suppose I want to change the color of the highlighted text to blue color, then first check if the highlighted text has a span. Secondly whether that span has color or background or even both styling. And lastly do the changes to the highlighted text.
$('#change_blue').on("click", function() {
var sel = getSelectionHtml();
/*var span = sel.find("<span").html();*/
alert(sel);
if (sel.match("<span style=")) {
console.log('has span tag');
if (sel.indexOf("background") > -1 && sel.indexOf("color") > -1 ) {
console.log('has both background and color')
// change color to blue
}
else if (sel.match("color")) {
console.log('only color')
// change color to blue
}
else {
console.log('only background')
// add blue color
}
}
else {
console.log('no span tag');
}
});
How can I get the html of a highlighted text and change it accordingly? It would really mean a lot if you could help me through. Thank you.
Demo
Do this,
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount, range; i < len; ++i) {
range = sel.getRangeAt(i);
if (range.startContainer === range.endContainer
&& range.startContainer.nodeType === Node.TEXT_NODE
&& range.startOffset === 0
&& range.endOffset === range.startContainer.length) {
range.selectNode(range.startContainer.parentElement);
}
container.appendChild(range.cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
I trying to do some validation on a form with radio buttons in it. I can get the text elements to work fine but the radio buttons don't seem to like me.
function validateAll(theForm)
{
var err=0;
var fields;
for (var i=0; i<theForm.elements.length; i++)
{
fields =theForm.elements[i];
if(fields.type == "text" || fields.type == "textarea")
{
if(fields.value == "" || fields.value == null){
err++;
validateText(fields.id);
}
}
else if(fields.type == "radio"){
validateRadio(fields)
}
}
if(err > 0){return;}else{document.myform.submit();}
}
function validateText(id)
{
var x=document.forms["myForm"][id].value;
if (x==null || x=="")
{
var text = id+"Text";
document.getElementById(text).style.visibility ="visible";
return;
}else {
var text = id+"Text";
document.getElementById(text).style.visibility="hidden";
return;
}
}
function validateRadio(radios)
{
var id = radios.id;
var text;
for (i = -1; i < radios.length; ++i)
{
if (radios[i].checked) {
text = id+"Text";
document.getElementById(text).style.visibility="hidden";
return true
}}
text = id+"Text";
alert(text);
document.getElementById(text).style.visibility ="visible";
return false;
}
I am just calling it with a input button. Any ideas on why its not working? It turns the text on find but dose not turn it off.