SPGuar
SPGuar

Reputation: 413

how to convert number to hexa string in js

I want to make a RGB to HEX converter using JS. to do this i did the below code:

function convertToHex(){

            var r=document.getElementById("R").value;
            var g=document.getElementById("G").value;
            var b=document.getElementById("B").value;


            if(r>255 || g>255 || b>255){
                document.getElementById("error").innerHTML='R ,G, B value can not be greater than 255';

            }
            else{
                var rHex=r.toString(16);
                var gHex=g.toString(16);
                var bHex=b.toString(16);

                var toHex=rHex+gHex+bHex;
                document.getElementById("hexContainer").innerHTML=toHex;
            }       

        }

but it is not working. Could you please help me. it is showing the numbers only not converted values.

Upvotes: 0

Views: 170

Answers (3)

Taiti
Taiti

Reputation: 377

You can try out this way. It works perfect.

<body>
 <input id="R" type="number">
 <br>
 <input id="G" type="number">
 <br>
 <input id="B" type="number">
 <br>
 <input id="btn" type="button"    onclick="rgb2hex()" value="calculate">
 <div id= "hexContainer"></div>
 <div id="error"></div>

<script>
function rgb2hex() {
var r = document.getElementById("R").value
    var g = document.getElementById("G").value
        var b =document.getElementById("B").value
 if (r> 255 || g> 255 || b> 255){
            document.getElementById( "error" ).innerHTML= 'R ,G, B value can not be greater than 255' ;
            document.getElementById( "hexContainer").innerHTML=""
        }
else {
document.getElementById( "hexContainer").innerHTML= ("#"+dec2Hex(Math.round(r)) +""+ dec2Hex(Math.round(g)) +""+dec2Hex(Math.round(b)));

document.getElementById( "error").innerHTML=""
}
 }
 function dec2Hex(decimal) {
return ("0"+(Number(decimal).toString(16))).slice(-2).toUpperCase()
}
  </script>
 </body>

Upvotes: 1

Monarch Wadia
Monarch Wadia

Reputation: 4996

function convertToHex(){

        var r=document.getElementById("R").value;
        var g=document.getElementById("G").value;
        var b=document.getElementById("B").value;


        if(+r>255 || +g>255 || +b>255){
            document.getElementById("error").innerHTML='R ,G, B value can not be greater than 255';

        }
        else{
            var rHex=(+r).toString(16);
            var gHex=(+g).toString(16);
            var bHex=(+b).toString(16);

            var toHex=rHex+gHex+bHex;
            document.getElementById("hexContainer").innerHTML=toHex;
        }       

    }

Upvotes: -1

davidhu
davidhu

Reputation: 10472

When you grab the value from HTML, you need to convert the string to number,

you can do

var r = Number(document.getElementById("R").value);

I tested the rest of the code, and they work fine.

Upvotes: 1

Related Questions