How to change color of a button in HTML (if a condition is satisfied) using JAVAscript?
Home / Blog / How to change color of a button in HTML (if a condition is satisfied) using JAVAscript?

How to change color of a button in HTML (if a condition is satisfied) using JAVAscript?

Changing the HTML button color is possible if you use CSS. Unlike JavaScript, the CSS interface is search engine and user- friendly. It is more accessible.

If your button is:

<input type="button" id="button1" value="Button" style="color:Red;" />

You should have this code to change the color:

if (x > 10)
 {
 e = document.getElementById("button1");
 if(null != e)
 {
 e.style.color = "Yellow";
 }
 }

If there is a space between the colour and #, you should remove it to change the colour. A correct code should be observed to make you successful in coding.

You should also be cautious in deactivating controls because it will mess us the form. Take in mind that JavaScrip doesn’t help. CSS does. You should insert the below codes in your headers to change the buttons colour.

<style>
#radios {
bg-color: red;
color: orange;
}
</style>

Or you can try these codes.

<form autocomplete="off">
<fieldset style="width: 10em">
<legend>Choose</legend>
<input type="radio" id="f1" name="num" value="1" onclick="tweakRadio( this )" />
<label for="f1">One</label>
<input type="radio" id="f2" name="num" value="2" onclick="tweakRadio( this )" />
<label for="f2">Two</label>
<input type="radio" id="f3" name="num" value="3" onclick="tweakRadio( this )" />
<label for="f3">Three</label>
</fieldset>
</form>
<script type="text/javascript">
 addElementLabels = function (f) {
 if (typeof f.getElementsByTagName == "undefined") return;
 var labels = f.getElementsByTagName( "label" );
 var i, label, elem;
 for (i = 0; i < labels.length; i++) {
 label = labels[ i ];
 if (typeof label.htmlFor == "undefined") return;
 elem = document.getElementById( label.htmlFor );
 if (typeof elem != "undefined") elem.label = label;
 }
 }
tweakRadio = function (elem) {
 var f = elem.form;
 var elemName = elem.name;
 var i, radio;
 for (var i = 0; i < f.elements[ elemName ].length; i++) {
 radio = f.elements[ elemName ][ i ];
 radio.disabled = false;
 if (typeof radio.label != "undefined") {
 radio.label.style.color = "#000";
 }
 }
 elem.disabled = true;
 if (typeof elem.label != "undefined") {
 elem.label.style.color = "#CCC";
 }
 }
addElementLabels( document.forms[ 0 ] );
 </script>

We can solve all programming assignments! Don’t hesitate! Call us today!