Skip to content Skip to sidebar Skip to footer

How Do I Use Html And Javascript To Add Elements To A Webpage?

I currently have some HTML and Javascript I'm using to try and make a comment section. Basically, what I want to accomplish is to have a form with either a textarea (preferred, and

Solution 1:

You're close:

  1. Move the onsubmit handler to the form element.
  2. getElementsByTagName returns a collection. To get the value of the input, use inputs[0].value.

Snippet

functionpostComment(input) {
  //Variable for the formvar form = input.parentElement;
  //Variable for text inputvar inputs = form.getElementsByTagName("input");
  //Variable for the value of the form and if condition met "then" do this if true "else" this if falsevar response = inputs[0].value;

  //Variables for creating a paragraph element and text per responsevar node = document.createElement("p"),
      textNode = document.createTextNode(response);

  //Adding the response text to the paragraph and appending that to the bottom of the form
  node.appendChild(textNode);
  form.appendChild(node);
}
<formonsubmit="postComment(this); return false;"><inputtype="text"><p>
    Comments Below:
  </p></form>

Here's how to do this with a textarea, using your Enter and Shift+Enter criteria:

document.addEventListener("DOMContentLoaded", function(event) {
  var form= document.querySelector('form');
  var textarea= document.querySelector('textarea');

  textarea.onkeypress= function(e) {
    if(e.which === 13 && !e.shiftKey) {
      this.parentNode.onsubmit(e);
    }
  }

  form.onsubmit= function(e) {
    var textarea = form.querySelector('textarea');
    var response = textarea.value;
    var node = document.createElement('div');
    node.innerHTML= response.replace(/\n/g,'<br>') + '<hr>';
    form.appendChild(node);
    textarea.value= '';
    e.preventDefault();
  }
});
textarea {
  width: 50%;
  height: 5em;
  float: left;
}

p {
  clear: both;
}
<form><textarea></textarea><inputtype="submit"><p>
    Comments Below:
  </p></form>

Post a Comment for "How Do I Use Html And Javascript To Add Elements To A Webpage?"