Rhys Edwards Rhys Edwards - 4 years ago 106
Javascript Question

Getting value from a console.log to html

The function I have written works fine and the value correctly writes to my terminal onSubmit, however I'm struggling to piece together why this code isn't updating my html.

router.post('/index', function(req, res, next) {

// ...Get form values, do calculations to get toCost value.

console.log('$' + toCost);

$(document).ready(function() {
var output = document.getElementById('cost');
output.innerHTML = toCost;
});

res.location('/');
res.redirect('/');
})


I receive the following error and jquery is loading fine.

$ is not defined


Admittedly this is an over-engineered node/express app. The code snippet lives wrapped in a route file, inside a post request.

How do I get my value onto the html?

Jade layout

extends layout

block content
form(...)
div#cost

Answer Source

The normal way to do this would be as follows:

router.post('/index', function(req, res) {   <<< 'next' removed (only needed if using middleware)

  // ...Get form values, do calculations to get toCost value.

  console.log('$' + toCost);

  res.render('indexTemplate', {cost: toCost}); <<< pass toCost through to jade as 'cost'
});

Then in your jade file for the indexTemplate you can reference the 'cost' variable passed in like this:

indexTemplate.jade:

extends layout

block content
  form(...)
  div#cost #{cost} <<< adds the cost variable to page

Then the value of toCost will appear in the resulting page.

No jQuery is required on the server side.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download