Empty value for adding 2 variables

<html>
<head>
<title>Variables</title>
    </head>
    
<body>
    
    <input id="num1" type="text">
    <input id="num2" type="text">
    <button  id="add"> add us</button>
    <script>
        var x = document.getElementById("num1").value
        var y = document.getElementById("num2").value
        
        var total = x + y
        
 document.getElementById ("add").onclick = function ()
 {
alert (total)
 }
 
 
    </script>
    </body>
    
</html>

what’s your question?


I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

I wrote this code but no output

thanks @ilenia

you are getting x and y at load of page, you need instead to get those values when the button is pressed

<html>
<head>
<title>Variables</title>
    </head>
    
<body>
    
    <input id="num1" type="text">
    <input id="num2" type="text">
    <button  id="add"> add us</button>
    <script>
       
        
 document.getElementById ("add").onclick = function ()
 {
      var x = parseFloat(document.getElementById("num1").value) 
        var y = parseFloat(document.getElementById("num2").value) 
        
      
        
        var total = x + y
        
alert (total)
    
 }
 
 
    </script>
    </body>
    
</html>

Thanks a lot, it’s working now :slight_smile:

awesome! good job!

happy coding

1 Like