Ecco un semplice convertitore binario, decimale, ottale e esadecimale:
Ed ecco il codice sorgente:
Questo codice è codice CSS, esso serve a definire lo stile della pagina html.
<style type="text/css"> body { background-color:transparent; } td,tr,table,input { background-color:transparent; } select { background-color: grey; color: white; } </style>
Questa funzione controlla se nel riquadro dei numeri decimali vengono digitati numeri e non lettere; in quest’ultimo, la funzione ritorna falso e non scrive alcun carattere.
<script type="text/javascript"> function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; }
Questa funzione controlla se l’utente digita nel box, binario,ottale o esadecimale, i numeri (o lettere in caso di esadecimale) del rispettivo sistema numerico.
function Key(evt) { var convertitore=document.getElementById('Convertitore'); var convert=convertitore.options[convertitore.selectedIndex].value; var charCode = (evt.which) ? evt.which : event.keyCode if(convert != 15) { if ((charCode >= 48 && charCode <= 48+parseInt(convert)) || charCode == 8) return true; return false; } else { if ((charCode >= 48 && charCode <= 58) || (charCode >=97 && charCode <= 102 )|| charCode == 8) return true; return false; } }
La funzione converti() converte i numeri da decimale al rispettivo sistema numerico o viceversa.
function converti(get) { var decimale=document.getElementById("decimale"); var ris=document.getElementById("risultato"); var convertitore=document.getElementById("Convertitore"); var convert=convertitore.options[convertitore.selectedIndex].value; if(get==1) { ris.value=parseInt(decimale.value).toString(parseInt(convert)+1); } if(get==2) { decimale.value=parseInt(ris.value, parseInt(convert)+1); } } </script>
Ecco infinite la struttura del programma scritta in html:
<form> <center> <table> <tr> <td>Decimale</td> <td><input type="text" id="decimale" OnKeypress="return isNumberKey(event)" OnKeyUp="converti(1)"></td> </tr> <tr><td><p style="height: 20px;"></p></td></tr> <tr> <td><select name="Convertitore" id="Convertitore" OnChange="converti(2)"> <option value="1">(2) Binario</option> <option value="7">(8) Ottale</option> <option value="15">(16) Esadecimale</option> </select> </td> <td><input type="text" id="risultato" OnKeyPress="return Key(event)" OnKeyUp="converti(2)"></td> </tr> </table> </form> </center>
Ti è piaciuto questo articolo? Allora ti piacerà anche:
– Verificare lo stato di un bottone in Javascript
– Hunting The Invaders un gioco creato in Javascript
– Creare una calcolatrice in Javascript