0

I'm trying to learn Javascript. Why this is not working?

function test() {
  var x,z;
  $x = document.getElementById("input").value;
  $z = ($x).toString(2);
  document.getElementById("demo").innerHTML = $z;
}
<input type="text" id="input">
<button onclick="test()">Try it</button>
<p id="demo"></p>

3
  • Browser don't inser binary number but it inser what is in input. Commented Feb 21, 2015 at 19:57
  • So you trying to convert the input number to binary number and then insert in p? Commented Feb 21, 2015 at 19:58
  • See my answer below... Commented Feb 21, 2015 at 20:00

2 Answers 2

2

Your $x is a string, not a number.

To convert it to a number, you can use the unary + operator.

Then, toString(2) will work:

function test() {
  var $x = +document.getElementById("input").value,
      $z = $x.toString(2);
  document.getElementById("demo").innerHTML = $z;
}
<input type="text" id="input">
<button onclick="test()">Try it</button>
<p id="demo"></p>

Sign up to request clarification or add additional context in comments.

1 Comment

+ though I will prefer to use (+$x).toString(2); where I need $x as int
0

You need to convert $x to int by parseInt() this way...

$z = (parseInt($x)).toString(2);

Modified Function...

function test() {
        var x,z;
        $x = +document.getElementById("input").value;
        $z = ($x).toString(2);
        document.getElementById("demo").innerHTML = $z;
    }

Working Fiddle

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.