Search code examples
javascripthtmlonclickconsole.logcreateelement

Basic javascript questions about onclicks, createElement and more?


I really don't understand why I'm running into so many little problems. The questions are also commented out in the javascript. Thanks a lot for any help!

1) How do I get and use the form's data outside createNote function?
2) Why does formArea, textArea and submitButton disappear from inside div1 on the click of submitButton?
3) Alert is appearing, why is it but not console.log?
4) No console log appearing, why?
5) Why isn't the 'p' tag showing up in div2?

html:

<!DOCTYPE html>
<html>
    <head>
        <title>Todo App</title>
        <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8">    
    </head>
    <body>
        <div id="div1"></div>
        <div id="div2"></div>

        <button id="newNote">Add Note</button>

        <script type="text/javascript" src="app.js"></script>
    </body>
</html>

css:

#div1 {
  width: 200px;
  height: 200px;
  border: solid 1px #000;
}

#div2 {
  width: 200px;
  height: 200px;
  border: solid 1px #000;
}

javascript:

var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
var newNote = document.getElementById("newNote");

var createNote = function(){
    var formArea = document.createElement("form"); formArea.id = "form_1";
    var textArea = document.createElement("textarea");
    var submitButton = document.createElement("button"); submitButton.innerHTML = "Submit";
    formArea.appendChild(textArea);
    formArea.appendChild(submitButton);
    div1.appendChild(formArea);
    var getValue = document.getElementById("form_1").value; // how do I get and use the form's data outside this function?

    submitButton.onclick = submitClicked; // why does formArea, textArea and submitButton disappear from inside div1 on the click of submitButton?
};

var submitClicked = function (){
    alert("asdf"); // alert is appearing, why is it but not console.log?
    console.log("asdf"); // no console log appearing, why?
    var paragraphArea = document.createElement("p"); // why isnt this showing up in div2?
    div2.appendChild(paragraphArea);
    paragraphArea.innerHTML = "asdf";
};

newNote.onclick = createNote;

Solution

  • When you click on a button that is inside a form, the form will be submitted automatically. This means a page reload. This is why your custom elements keep disappearing and why the alert kicks in. The console log was printed, but then removed on refresh (you can verify this by turning on the 'Preserve Log' feature on the console in Chrome)

    To handle this, in your submitClicked function, you need to prevent the default behavior of the form. Something like,

    var submitClicked = function(event) {
        event.preventDefault();
        ... Rest of the code.
    }