SPGuar SPGuar - 1 year ago 66
Javascript Question

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';

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

var toHex=rHex+gHex+bHex;


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download