The Beast
The Beast

Reputation: 1

Update div when writing text does not work as expected

My goal is to write content in a textarea and display exactly what I am writing without have to refresh the page each letter that I type shows immediately well it is not working for some reason.

HTML:

 <textarea id="Q&A" name="txtarea" rows="4" cols="50"></textarea>
 <div id="out"></div>

Js:

function generate() {
  var reader = new commonmark.Parser();
  var writer = new commonmark.HtmlRenderer();
  var parsed = reader.parse(text);
  text = writer.render();
  document.getElementById("out").innerHTML = text
}

document.getElementById("Q&A").addEventListener("input", function () {
    generate(this.value);
});

When I try to update the div with the id of out to what I am typing using JavaScript, it does not work.

Upvotes: 1

Views: 58

Answers (2)

Shyju
Shyju

Reputation: 218722

I don't know what the commonmark.Parser() does in your code. But the issue i see is, When you are calling the generate method, you are passing the value of the input field. But in your generate method signature, you don't have a parameter to accept that.

Add a parameter to your generate() method to accept the value passed in.

function generate(text) {
   //do something else on text with your commonmark
   document.getElementById("out").innerHTML = text;
}

Here is a working sample.

and you forgot to pass the argument parsed to the render function:

You had: text = writer.render(); I changed it to text = writer.render(parsed);

Upvotes: 2

The Beast
The Beast

Reputation: 1

I figured it out i forgot to have text pasted in as a argument in the generate function and I forgot to pas parsed into the render function

Here is the final code:

function generate(text) {
  var reader = new commonmark.Parser();
  var writer = new commonmark.HtmlRenderer();
  var parsed = reader.parse(text);
  text = writer.render(parsed);
  document.getElementById("out").innerHTML = text
}

document.getElementById("Q&A").addEventListener("input", function () {
    generate(this.value);
});

Upvotes: 1

Related Questions