How to store the value of an input type number in a JS variable

Asked

Viewed 341 times

2

I cannot store input value in my variable. How should I proceed? My code below:

<input type="number" id="numero">
<input type="button" class="adicionar" value="Comprar" onclick="add()" />

<script>
    function add(){
        var quantidade = parseInt(document.getElementById('numero').value); 
        console.log("Value: "+quantidade);
</script>

I want to change the value of the input and my variable change also when I click the button.

2 answers

2

All you have to do is close the keys, but there is a property onchange. With the property onchange each time you change the value of the input it calls its function add(), thus altering together the input it will change its variable together;

<input type="number" id="numero" onchange="add()">
<input type="button" class="adicionar" value="Comprar" onclick="add()">

<h1 id="valor"></h1>

<script>
    function add(){
        var quantidade = parseInt(document.getElementById('numero').value); 
        console.log("Value: "+quantidade);
        document.getElementById('valor').innerHTML = quantidade;
        }
</script>

  • It’s true, it worked. Thank you very much!

1

You missed closing the keys.

<input type="number" id="numero">
<input type="button" class="adicionar" value="Comprar" onclick="add()" />

<script>
    function add(){
        var quantidade = parseInt(document.getElementById('numero').value); 
        console.log("Value: "+quantidade);
        }
</script>

  • True, silly mistake. Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.