bldzrr
bldzrr

Reputation: 13

Updating javascript variable on html page through html button click?

I'm making a basic program where the user is shown a current room temperature along with a text field and "Set" button so that they can set their desired room temperature. What I want to happen is when the user enters a number into the text field and hits the Set button it changes the "roomTemp" variable to their desired temperature also known as "desiredTemp" and displays it as the current temperature. I don't think it's reaching the save() function as nothing is printed in my console when the button is clicked when it should output "Temperature is changing!" to my console.

Javascript File:

var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var roomTemp = 20;
var desiredTemp = 0;

http.createServer(function(req,res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  //since we are in a request handler function
  //we're using readFile instead of readFileSync
  fs.readFile('index.html', 'utf-8', function(err, content) {
    if (err) {
      res.end('error occurred');
      return;
    }

    var renderedHtml = ejs.render(content, {roomTemp: roomTemp});  //get redered HTML code
    res.end(renderedHtml);
  });
}).listen(3000, "127.0.0.1");
console.log('Server Running at http://127.0.0.1:3000  CNTL-C to quit');

HTML File:

<!DOCTYPE html>
<html>
<head>
<script src="Thermostat.js"></script>
</head>
<body>

Current Temp: <%= roomTemp %> <br></br>

<form>
Desired Room Temperature: <input type="number" id="desTemp" name="roomTempDes"><br></br>
<button onclick="save(document.getElementById("roomTempDes").value)">Set</button>
</form>

<script>
function save(desiredTemp) {
      roomTemp = desiredTemp;
      console.log("Temperature is changing!");
}
</script>

</body>
</html>

Upvotes: 0

Views: 394

Answers (2)

scunliffe
scunliffe

Reputation: 63686

Your code is quoted incorrectly AND you have the WRONG ID.

<button onclick="save(document.getElementById('desTemp').value)">Set</button>

Upvotes: 0

Pieter De Bie
Pieter De Bie

Reputation: 1212

You have too many quotation marks in your script.

"save(document.getElementById("roomTempDes").value)"

should be

"save(document.getElementById('roomTempDes').value)"

Upvotes: 2

Related Questions