DEV Community

Discussion on: How to Build Binary to Decimal Converter Using JavaScript

Collapse
lukeshiru profile image
LUKESHIRU • Edited

There is another approach that is quite simpler, and relies more in HTML5. Only 2 steps:

  • First: Add a pattern in the input, so it only allows 0 and 1 and make it required. You might also need to add a title so it has a good description when the pattern doesn't match:
<input
    autocomplete="off"
    id="input"
    name="bin"
    pattern="[0|1]+"
    placeholder="Binary No."
    required
    title="You should enter a binary number composed by 0 and 1"
    type="text"
/>
Enter fullscreen mode Exit fullscreen mode
  • Second: Listen to the submit event of the form instead of listening to the click even in the button (because we are doing this, remember the type of button needs to be submit), no need to validate because that was done by the input already, so this is all the JS code you need:
const form = document.querySelector("form");

form.addEventListener("submit", event => {
    event.preventDefault();
    output.value = parseInt(input.value, 2);
});
Enter fullscreen mode Exit fullscreen mode

As you might notice, we used parseInt instead of implementing a custom logic, because is more than enough to parse a binary to decimal by setting the radix value (the second argument) to 2.

Cheers!

Collapse
stackfindover profile image
Stackfindover Author

Awesome, Thanks for your suggestion bro :)