pits
pits

Reputation: 1

html button and javascript code

Ok. I make a program for calculating the power of 2. I have the html code . But i describe it for you first. There is one input with id='inputin' and below there is a button. In the input you write a number . This number will be the exponent of two and after you push the button it appears a console.log window with the result

here the html :

<div id='main'>
    <input type="number" name="power2" placeholder='Enter the power' id='inputin'><br/>
    <button id="submit" onclick="binaryS()">Do it!</button>

    </div>

and the javascript:

binaryS = function() {
x = document.getElementById("inputin").value;
y=1;
for(i=1;i<=x;i++) {
    y=y*2;
}
console.log (y);
};

Why it doesnt work? Any help? and if you could suggest instead of an ugly console.log window how can i appear it in a new div somewhere in the page? Thnx

Upvotes: 0

Views: 260

Answers (3)

user2377782
user2377782

Reputation:

Without getting into details, your code is working. I have made a single html page to demonstrate it:

<html>
    <head>
        <script type="application/x-javascript">
            binaryS = function() {
                x = document.getElementById("inputin").value;
                y=1;
                for(i=1;i<=x;i++) {
                    y=y*2;
                }
                document.getElementById('result').innerHTML = y
            };
        </script>
    </head>
    <body>
        <div id='main'>
            <input type="number" name="power2" placeholder='Enter the power' id='inputin'><br/>
            <button id="submit" onclick="binaryS()">Do it!</button>
        </div>
        <div id="result" ></div>
    </body>
</html>

I also would suggest you using Math.pow instead of a custom math calculation:

Math.pow( 2, parseInt(document.getElementById("inputin").value));

Upvotes: 0

user1641172
user1641172

Reputation:

Your JavaScript should be:

function binaryS() {
   var x = document.getElementById("inputin").value;
   document.getElementById("outputValue").innerHTML = Math.pow(2,x);
}

Place the following somewhere on your page for the display:

<div id="outputValue">Result</div> 

Upvotes: 7

Learner
Learner

Reputation: 4004

Try this function:

function nearestPow2(){
  return Math.pow(2, Math.round(Math.log(document.getElementById("inputin").value;) / Math.log(2))); 
}

Ref: http://weblog.bocoup.com/find-the-closest-power-of-2-with-javascript/

Upvotes: 1

Related Questions