/    Sign up×
Community /Pin to ProfileBookmark

Form input background color change based on the number inside it

I need to make form input background color change based on the number inside it everytime it is changed by user **or by script**. So far I’ve made one script myself, but it is not working as expected, it is changing only color of the input user is typing in and for some reason only after he focuses on it second time. My script here `function changeColor() {
document.getElementById(“form1”).childNodes.forEach(inputVal=>{
inputVal.addEventListener(‘input’,event=>{
if (inputVal.value == “0”) {
inputVal.setAttribute( ‘style’, ‘border: 4px solid #009900 !important;’);
inputVal.setAttribute( ‘style’, ‘background-color: rgba(40, 74, 14, 0.45) !important;’);
}
else if (inputVal.value == “1”) {
inputVal.setAttribute( ‘style’, ‘border: 4px solid #f5d442 !important;’);
}
});
});
}`

**END OF IMPORTANT THINGS**

*Any help greately appreciated*
Btw, this is my first time here! (Seemed much friendlier here then on stackoverflow)

to post a comment
CSSHTMLJavaScript

18 Comments(s)

Copy linkTweet thisAlerts:
@SempervivumJun 12.2020 — Hi zxx54 and welcome to the forum!

I didn't test your code yet but one issue seems to be obvious: When setting the attribute `style</C> this will assign the new value and overwrite everything that has been assigned before.<br/>
Solutions:<br/>
a) Assign all rules in one instruction like this:<br/>
<C>
inputVal.setAttribute( 'style', 'border: 4px solid #009900; background-color: rgba(40, 74, 14, 0.45);');`


or

b) Assign the rules separately like this:
inputVal.style.border = '4px solid #009900';
inputVal.style.backgroundColor = 'rgba(40, 74, 14, 0.45)';


I prefer the second option as it is not necessary to remember rules that have been assigned before.

AFAIK in this case !important is not necessary as rules being set by javascript already have the highest priority.
Copy linkTweet thisAlerts:
@cootheadJun 12.2020 — @zxx54,

personally, I believe that it is preferable to remove

**style** from the JavaScript, as in this example...
``<i>
</i>&lt;!DOCTYPE HTML&gt;
&lt;html lang="en"&gt;
&lt;head&gt;

&lt;meta charset="utf-8"&gt;
&lt;meta name="viewport" content="width=device-width,height=device-height,initial-scale=1"&gt;

&lt;title&gt;Untitled Document&lt;/title&gt;

&lt;!--&lt;link rel="stylesheet" href="screen.css" media="screen"&gt;--&gt;

&lt;style media="screen"&gt;
label, input[type="number"] {
display: block;
margin: 0.5em 0;
}
input[type="number"] {
width: 3em;
font-size: 1em;
text-align: center;
}
.zero {
border: 0.25em solid #090;
background-color: rgba( 40, 74, 14, 0.45 );
}
.one {
border: 0.25em solid #f5d442 ;
}

&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;
&lt;form id="form1" action="#"&gt;
&lt;label for="inp1"&gt;input 1&lt;/label&gt;
&lt;input id="inp1" class="zero" type="number" min="0" max="1" value="0"&gt;
&lt;label for="inp2"&gt;input 2&lt;/label&gt;
&lt;input id="inp2" class="zero" type="number" min="0" max="1" value="0"&gt;
&lt;label for="inp3"&gt;input 3&lt;/label&gt;
&lt;input id="inp2" class="zero" type="number" min="0" max="1" value="0"&gt;
&lt;/form&gt;

&lt;script&gt;
( function( d ) {
'use strict';

var c, inps,frm = d.getElementById( 'form1' );

frm.reset();

inps = frm.querySelectorAll( 'input[ type="number" ]' );

for ( c = 0; c &lt; inps.length; c ++ ){
inps[ c ].addEventListener( 'change', styleInput( c ), false );

}

function styleInput( c ) {
inps[ c ].onchange = function(){
if ( inps[c].value === '0' ) {
inps[c].classList.remove( 'one' );
inps[c].classList.add( 'zero' );
}
else {
inps[c].classList.remove( 'zero' );
inps[c].classList.add( 'one' );
}
}
}
} ( document ) );
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;

_coothead_<i>
</i>
``
Copy linkTweet thisAlerts:
@zxx54authorJun 13.2020 — Thank you guys, you improved my code a lot, but one issue still remains. In my webpage, user changes only the first input field, and every other is changed by javascript and I need color of those to change too. Could anyone please help me to make my script change the fields color event when its not changed by user?
Copy linkTweet thisAlerts:
@zxx54authorJun 13.2020 — User enters input in first input field, then press enter and his input moves one input box down, while color of every input box is based on the value inside it. But it doesn't work. Can someone please please fix it for me? Thank you

This is my full script in pure JavaScript

<br/>
var inputs;<br/>
inputs = document.getElementsByClass('cisla');<br/>
inputs.type = 'text';<br/>
/*<br/>
Zelená = #009900 Červená #bf2a2a Černá #000000<br/>
*/<br/>
if (inputs.value == "0") {<br/>
inputs.setAttribute( 'style', 'border: 4px solid #009900;');<br/>
inputs.setAttribute( 'style', 'background-color: rgba(40, 74, 14, 0.45);');<br/>
}<br/>
else if (inputs.value == "1") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "2") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "3") {<br/>
inputs.style.border = '4px solid #bf2a2a';<br/>
inputs.style.backgroundColor = 'rgba(191, 42, 42, 0.45)';<br/>
}<br/>
else if (inputs.value == "4") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "5") {<br/>
inputs.style.border = '4px solid #bf2a2a';<br/>
inputs.style.backgroundColor = 'rgba(191, 42, 42, 0.45)';<br/>
}<br/>
else if (inputs.value == "6") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "7") {<br/>
inputs.style.border = '4px solid #bf2a2a';<br/>
inputs.style.backgroundColor = 'rgba(191, 42, 42, 0.45)';<br/>
}<br/>
else if (inputs.value == "8") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "9") {<br/>
inputs.style.border = '4px solid #bf2a2a';<br/>
inputs.style.backgroundColor = 'rgba(191, 42, 42, 0.45)';<br/>
}<br/>
else if (inputs.value == "10") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "11") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "12") {<br/>
inputs.style.border = '4px solid #bf2a2a';<br/>
inputs.style.backgroundColor = 'rgba(191, 42, 42, 0.45)';<br/>
}<br/>
else if (inputs.value == "13") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "13") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(0, 0, 0, 0.45)';<br/>
}<br/>
else if (inputs.value == "13") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(40, 74, 14, 0.45)';<br/>
}<br/>
else if (inputs.value == "13") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(40, 74, 14, 0.45)';<br/>
}<br/>
else if (inputs.value == "13") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(40, 74, 14, 0.45)';<br/>
}<br/>
else if (inputs.value == "13") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(40, 74, 14, 0.45)';<br/>
}<br/>
else if (inputs.value == "13") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(40, 74, 14, 0.45)';<br/>
}<br/>
else if (inputs.value == "13") {<br/>
inputs.style.border = '4px solid #000000';<br/>
inputs.style.backgroundColor = 'rgba(40, 74, 14, 0.45)';<br/>
}<br/>
else {<br/>
inputs.style.border = '4px solid #ccc';<br/>
inputs.style.backgroundColor = 'rgba(40, 74, 14, 0.45)';<br/>
}

window.onload = function() {<br/>
var cislainput = document.getElementById('cisla');<br/>
cislainput.type = 'text';<br/>
cislainput.removeAttribute('autocomplete');<br/>
var src1 = document.getElementById("cislo1"),<br/>
src2 = document.getElementById("cislo2"),<br/>
src3 = document.getElementById("cislo3"),<br/>
src4 = document.getElementById("cislo4"),<br/>
src5 = document.getElementById("cislo5"),<br/>
src6 = document.getElementById("cislo6"),<br/>
src7 = document.getElementById("cislo7"),<br/>
src8 = document.getElementById("cislo8"),<br/>
src9 = document.getElementById("cislo9"),<br/>
src10 = document.getElementById("cislo10"),<br/>
src11 = document.getElementById("cislo11"),<br/>
src12 = document.getElementById("cislo12");<br/>
src1.addEventListener("keyup", event =&gt; {<br/>
if (event.isComposing || event.keyCode === 13) {<br/>
src12.value = src11.value;<br/>
src11.value = src10.value;<br/>
src10.value = src9.value;<br/>
src9.value = src8.value;<br/>
src8.value = src7.value;<br/>
src7.value = src6.value;<br/>
src6.value = src5.value;<br/>
src5.value = src4.value;<br/>
src4.value = src3.value;<br/>
src3.value = src2.value;<br/>
src2.value = src1.value;<br/>
src1.value = "";<br/>
zmenitBarvu()<br/>
}<br/>
});<br/>
};

var elem = document.documentElement;

document.addEventListener('keyup', function(e){<br/>
if(e.keyCode == 106) /* Vymazat čísla při stisknutí hvězdičky */<br/>
var src01 = document.getElementById("cislo1"),<br/>
src02 = document.getElementById("cislo2"),<br/>
src03 = document.getElementById("cislo3"),<br/>
src04 = document.getElementById("cislo4"),<br/>
src05 = document.getElementById("cislo5"),<br/>
src06 = document.getElementById("cislo6"),<br/>
src07 = document.getElementById("cislo7"),<br/>
src08 = document.getElementById("cislo8"),<br/>
src09 = document.getElementById("cislo9"),<br/>
src010 = document.getElementById("cislo10"),<br/>
src011 = document.getElementById("cislo11"),<br/>
src012 = document.getElementById("cislo12");<br/>
src01.value = "";<br/>
src02.value = "";<br/>
src03.value = "";<br/>
src04.value = "";<br/>
src05.value = "";<br/>
src06.value = "";<br/>
src07.value = "";<br/>
src08.value = "";<br/>
src09.value = "";<br/>
src010.value = "";<br/>
src011.value = "";<br/>
src012.value = "";

})

document.addEventListener('keyup', function(e){<br/>
if(e.keyCode == 107) /* Full screen při stisknutí + */<br/>
elem.webkitRequestFullscreen();<br/>
})

document.addEventListener('keyup', function(e){<br/>
if(e.keyCode == 109) /* Odejít z full screen při stisknutí - */<br/>
document.webkitExitFullscreen();<br/>
})<br/>
Copy linkTweet thisAlerts:
@SempervivumJun 13.2020 — This line:

`inputs = document.getElementsByClass('cisla');</C><br/>
enters a node<STRONG>**list**</STRONG> into the variable <C>
inputs`
. You need to use a loop to process all entries in that list:
inputs = document.getElementsByClass('cisla');
inputs.forEach(function(theinput) {
// parameter theinput contains the current input
// do with it whatever you like
});
Copy linkTweet thisAlerts:
@KeverJun 13.2020 — The change and input event only listen to value changes caused by user actions, not to those made by javascript.

Here's some code for inspiration.
<i>
</i>&lt;style&gt;
input[value="1"] {
background: #f00;
}
input[value="2"] {
background: #0f0;
}
input[value="3"] {
background: #00f;
}
&lt;/style&gt;

&lt;input type="text"&gt;

&lt;script&gt;
document.querySelector('input').addEventListener('input', function() {
this.setAttribute('value', this.value);
});
&lt;/script&gt;
Copy linkTweet thisAlerts:
@zxx54authorJun 13.2020 — @Kever#1619476 Thank you, I use this now, but i get <a class='gotoLine' href='#286:10'>286:10</a> TypeError: document.querySelector(...) is null

What could have caused it?
Copy linkTweet thisAlerts:
@zxx54authorJun 14.2020 — @coothead#1619458 Hey, I'll use this, but could you please make the script trigger even when input is changed by JavaScript, not just by the user?

Edit: And it triggers only once, could you make it trigger everytime something change?
Copy linkTweet thisAlerts:
@SempervivumJun 14.2020 — make the script trigger even when input is changed by JavaScript, not just by the user?[/quote]
After some research I found this thread at Stackoverflow:

https://stackoverflow.com/questions/32383349/detect-value-change-in-input-tag-with-vanilla-javascript-and-mutationobserver

where `Shawn Regan` posts a function that makes an input react on value changes by javascript.

I made a test file and it worked fine:
&lt;!DOCTYPE HTML&gt;
&lt;html lang="de"&gt;

&lt;head&gt;
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
&lt;title&gt;Colorise Inputs&lt;/title&gt;
&lt;style&gt;
&lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;!-- Your form as defined in your jsfiddle --&gt;
&lt;form id="cisla"&gt;
&lt;input name="cislo1" value="" type="text" class="cisla" placeholder="" id="cislo1" autofocus /&gt;&lt;br&gt;
&lt;input name="cislo2" value="" type="text" class="cisla" placeholder="" id="cislo2" /&gt;&lt;br&gt;
&lt;input name="cislo3" value="" type="text" class="cisla" placeholder="" id="cislo3" /&gt;&lt;br&gt;
&lt;input name="cislo4" value="" type="text" class="cisla" placeholder="" id="cislo4" /&gt;&lt;br&gt;
&lt;input name="cislo5" value="" type="text" class="cisla" placeholder="" id="cislo5" /&gt;&lt;br&gt;
&lt;input name="cislo6" value="" type="text" class="cisla" placeholder="" id="cislo6" /&gt;&lt;br&gt;
&lt;input name="cislo7" value="" type="text" class="cisla" placeholder="" id="cislo7" /&gt;&lt;br&gt;
&lt;input name="cislo8" value="" type="text" class="cisla" placeholder="" id="cislo8" /&gt;&lt;br&gt;
&lt;input name="cislo9" value="" type="text" class="cisla" placeholder="" id="cislo9" /&gt;&lt;br&gt;
&lt;input name="cislo10" value="" type="text" class="cisla" placeholder="" id="cislo10" /&gt;&lt;br&gt;
&lt;input name="cislo11" value="" type="text" class="cisla" placeholder="" id="cislo11" /&gt;&lt;br&gt;
&lt;input name="cislo12" value="" type="text" class="cisla" placeholder="" id="cislo12" /&gt;&lt;br&gt;
&lt;/form&gt;
&lt;button id="change-val"&gt;Change Value&lt;/button&gt;
&lt;script&gt;
// object containing background color
// for each value of the input
const colors = {
'1': 'lightblue',
'2': 'lightgrey',
'3': 'lightsalmon',
'4': 'lightgreen',
'5': 'yellow'
}
var registered = [];

<i> </i> // detect value change by javascript
<i> </i> // source for this function:
<i> </i> // https://stackoverflow.com/questions/32383349/detect-value-change-in-input-tag-with-vanilla-javascript-and-mutationobserver
<i> </i> var setDetectChangeHandler = function (field) {
<i> </i> if (!registered.includes(field)) {
<i> </i> var superProps = Object.getPrototypeOf(field);
<i> </i> var superSet = Object.getOwnPropertyDescriptor(superProps, "value").set;
<i> </i> var superGet = Object.getOwnPropertyDescriptor(superProps, "value").get;
<i> </i> var newProps = {
<i> </i> get: function () {
<i> </i> return superGet.apply(this, arguments);
<i> </i> },
<i> </i> set: function (t) {
<i> </i> var _this = this;
<i> </i> setTimeout(function () { _this.dispatchEvent(new Event("change")); }, 50);
<i> </i> return superSet.apply(this, arguments);
<i> </i> }
<i> </i> };
<i> </i> Object.defineProperty(field, "value", newProps);
<i> </i> registered.push(field);
<i> </i> }
<i> </i> }

<i> </i> document.querySelectorAll('#cisla input').forEach((item, idx) =&gt; {
<i> </i> setDetectChangeHandler(item);
<i> </i> item.addEventListener('change', (event) =&gt; {
<i> </i> const inp = event.target;
<i> </i> inp.style.backgroundColor = colors[inp.value];
<i> </i> });
<i> </i> });

<i> </i> // The following code only for testing
<i> </i> // that the colorising works when the value
<i> </i> // is changed by javascript
<i> </i> let val = 1;
<i> </i> const firstInput = document.getElementById('cislo1');
<i> </i> document.getElementById('change-val').addEventListener('click', () =&gt; {
<i> </i> firstInput.value = val;
<i> </i> val++;
<i> </i> if (val &gt; 5) val = 1;
<i> </i> });
<i> </i>&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
Note that the test button affects the first input only.
Copy linkTweet thisAlerts:
@zxx54authorJun 14.2020 — @Sempervivum#1619509 Thank you, this solution is brilliant, I'll use it.
Copy linkTweet thisAlerts:
@zxx54authorJun 14.2020 — @Sempervivum#1619509 One last thing, if I want to add more input colors how do I do it? I've tried to just put them inside const colors = {} but it didn't work.
Copy linkTweet thisAlerts:
@SempervivumJun 14.2020 — Yes, you will have to extend the object colors. If your attempt failed, please post the code.
Copy linkTweet thisAlerts:
@zxx54authorJun 14.2020 — Code here, did I made a mistake somewhere? I've only extended those colors. Is it red, green and black not a valid option?

https://jsfiddle.net/zyx54/c4wmuf6o/
Copy linkTweet thisAlerts:
@SempervivumJun 14.2020 — Have a look at the console if something doesn't work, in many cases it will tell you about the error.

Comma is missing here:

`'5': 'red'`

However when I correct this it doesn't work either. Gonna look into closer ...
Copy linkTweet thisAlerts:
@SempervivumJun 14.2020 — The same error at value '20'. After having corrected this the script works fine.
Copy linkTweet thisAlerts:
@zxx54authorJun 14.2020 — @Sempervivum#1619525 My bad, now everything works! Thank you so much
Copy linkTweet thisAlerts:
@ByrgersunJul 15.2020 — What do you think about this tool the Color Picker [https://chrome.google.com/webstore/detail/rainbow-color-picker/mlcjgkkpemdfclhfehjpgaaagkfpnnki](https://chrome.google.com/webstore/detail/rainbow-color-picker/mlcjgkkpemdfclhfehjpgaaagkfpnnki) I want to choose a convenient and simple plugin for Google. I need your advice.
Copy linkTweet thisAlerts:
@VITSUSAJul 16.2020 — @zxx54#1619526 I hope you must have found the solution.
×

Success!

Help @zxx54 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...