Advertisement
Lulunga

2. Number Convertor Exercise: DOM

Oct 12th, 2019
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve() {
  2.     // create TO options: : Binary and Hexadecimal
  3.     // create functions to convert decimal to binary and decimal to hexadecimal.
  4.     //  When the [Convert it] button is clicked, the expected result should appear in the [Result] input field.
  5.  
  6.     const selectMenuTo = document.getElementById('selectMenuTo');
  7.     document.querySelector("#container > button").addEventListener('click', convert);
  8.     function convert() {
  9.         let number = Number(document.getElementById('input').value);
  10.         let result;
  11.         if (selectMenuTo.value === 'binary') {
  12.             result = decimalToBinary(number);
  13.         } else if (selectMenuTo.value === 'hexadecimal') {
  14.             result = decimalToHexadecimal(number);
  15.         }
  16.         appendResult(result);
  17.     }
  18.     function appendResult(result) {
  19.         document.getElementById('result').value = result;
  20.     }
  21.     function decimalToBinary(number) {
  22.         return (number >>> 0).toString(2);
  23.     }
  24.     function decimalToHexadecimal(number) {
  25.         return number.toString(16).toUpperCase();
  26.     }
  27.  
  28.     function createSelectMenuOptions() {
  29.         let binaryOption = document.createElement('option');
  30.         binaryOption.textContent = 'Binary';
  31.         binaryOption.value = 'binary';
  32.         let hexadecimalOption = document.createElement('option');
  33.         hexadecimalOption.textContent = 'Hexadecimal';
  34.         hexadecimalOption.value = 'hexadecimal';
  35.  
  36.         selectMenuTo.appendChild(binaryOption);
  37.         selectMenuTo.appendChild(hexadecimalOption);
  38.     };
  39.     createSelectMenuOptions();
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement