The JS code is working swell, although it makes some risky assumptions. The problem you have is that you submit the form with that button, so the whole page reloads and you can't see the results.
This will force the form not to submit itself and there you go - problem solved!
However i have a few notes about good practices:
- don't use <center> tag in HTML5, as it is not supported anymore: center
- when you are accessing the value of #decimal, it's type is string and then you compare it with a number (0). If you expect a number, you should use:
var x = document.getElementById("decimal").value;
x = parseInt( x, 10 );
which will try to convert it to a decimal integer.
- this is just a matter of preference, but i don't like to see JS mixed up with HTML, so you can study something about unobtrusive javascript
also, converting between number bases could be as simple as:
var x = parseInt( document.getElementById("decimal").value, 10 );
document.getElementById("display").innerHTML = x.toString( 2 );
Your function is right !
But you have not to submit the form. Delete the onsubmit in the form and change the button submit with a input type="button" and an onclick="myfunction()"
You can verify with the toString(radix) method ans something like (+x).toString(2) (with a plus sign before to convert your read value to Number)
I don't like using a form without a submit button. After all, it's a form and when you are done with it, you should submit it; that's the default action. Your suggestion should work as expected after clicking on the button, but if you'd use the <button> tag without type, it would default to type=submit. Also, different browsers handle this differently and i bet, that some of them try to submit form with any button, that they find. Also, pressing enter will still submit the form, so without a handler for that, you lose the ability to confirm your input with enter.
@sam_mccool:
Another good practice is to enclose the attribute values of HTML tags in quotes. Although HTML5 does not require this, XHTML does, so it's best to get used to that, in case you will ever develop for XHTML...
If you are happy with the solution: Top of the comments > Thread Tools > Mark Thread Resolved
Bookmarks