1

so I've got a bit of the problem. I am trying to make a function in wich : human clicks on input box with mouse and types some random numbers in bytes and that number should be convert and shown in two other boxes such as MegaBytes and KiloBytes. So my problem is that Javascript shows me error :

Cannot set property 'value' of null
at convert (script.js:7)
at HTMLInputElement.onkeyup

here is my code so far:

function convert(inputas)
{
    var i;
    if(inputas == "B")
    {
        i = document.getElementById("baitas").value / 1000;
        document.getElementById("kiloBaitas").value = i;
    }
    else if(inputas == "KB")
    {
        i = document.getElementById("kiloBaitas").value * 1024;
        document.getElementById("baitas").value = i.toFixed(2);
    }
}

HTML code:

<input type="text" id="baitas" onkeyup="convert('B')placeholder="Bits">
<input type="text" id="kilobaitas"     
`onkeyup="convert('KB')"placeholder="Kilobits">
 <input type="text" id="megabaitas" onkeyup="convert('MB')" 
placeholder="Mbits">
<script src="script.js"></script>
Lucas
  • 37
  • 6

3 Answers3

1

when comparing your javascript with the html. the kilobaitis element is not spelt with a consistent case.

Stephen Quan
  • 15,118
  • 3
  • 69
  • 63
1

JavaScript is case sensitive.

function convert(inputas) {
  var i;
  if (inputas == "B") {
    i = document.getElementById("baitas").value / 1000;
    document.getElementById("kilobaitas").value = i;
  } else if (inputas == "KB") {
    i = document.getElementById("kiloBaitas").value * 1024;
    document.getElementById("baitas").value = i.toFixed(2);
  }
}
<input type="text" id="baitas" onkeyup="convert('B')" placeholder=" Bits ">
<input type="text " id="kilobaitas" onkeyup="convert('KB')" placeholder="Kilobits ">
<input type="text " id="megabaitas" onkeyup="convert('MB')" placeholder="Mbits ">
kind user
  • 32,209
  • 6
  • 49
  • 63
0

(function() {

var elems = [],
    elemsId = ['baitas','kilobaitas','megabaitas'];

function fix(a){ return ( a * 100 | 0 ) / 100  }

function convert(inputas)
{
    var i;
    switch(inputas)
    {
        case 0:
            i = elems[0].value;
            elems[1].value = fix( i / 1024 );
            elems[2].value = fix( i / 1048576 );
            break;
        case 1:
            i = elems[1].value;
            elems[0].value = i * 1024;
            elems[2].value = fix( i / 1024 );
            break;
        case 2:
            i = elems[2].value;
            elems[0].value = i * 1048576;
            elems[1].value = i * 1024;
            break;
    }
}

for (var i=0; i < elemsId.length; i++)
{
    elems[i] = document.getElementById( elemsId[i] );
    elems[i].addEventListener('keyup', convert.bind(null, i) )
}

}());
<input type="text" id="baitas" placeholder=" Bits">
<input type="text" id="kilobaitas" placeholder=" Kilobits">
<input type="text" id="megabaitas" placeholder=" Mbits">
MypKOT-1992
  • 181
  • 3