1

I am a total beginner and am learning front-end using a "just do it" and project-focus route.

My web app will essentially work similar to that of a to-do list.

I assume it is because I have "getElementById" twice for the same element.

This works initially:

// add idea to list button

document.getElementById('btnSubmit').addEventListener("submitIdea", submitIdea);

function submitIdea() {
    var ul = document.getElementsByClassName('anIdea')[0];
    var enterIdea = document.getElementById('enterIdea');
    var li = document.createElement('li');
    li.setAttribute('class', enterIdea.value);            
    li.appendChild(document.createTextNode(enterIdea.value));
    ul.prepend(li);
    li.contentEditable = 'true';
};

But then, when I add this code, I am unable to write anything at all in my input box:

// use enter key to submit new li item

document.getElementById("enterIdea").addEventListener('keypress', function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById('btnSubmit').click();
    }
});

These are the resources I used:

halfer
  • 19,824
  • 17
  • 99
  • 186
AelaHuntress
  • 61
  • 2
  • 9

2 Answers2

0

Instead of trying to "click" the button with javascript, simply call the desired function on the enter key press.

document.addEventListener("keypress", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById('btnSubmit').click();
    }
});
Ben Botvinick
  • 2,837
  • 3
  • 16
  • 41
0

your code is ok in general

document.getElementById('btnSubmit').addEventListener("click", function() {
  var ul = document.getElementsByClassName("anIdea")[0];
  var enterIdea = document.getElementById("enterIdea");
  var li = document.createElement("li");
  li.setAttribute('class', enterIdea.value);
  li.contentEditable = "true";
  li.appendChild(document.createTextNode(enterIdea.value));
  ul.prepend(li);
});

document.getElementById("enterIdea").addEventListener("keypress", function(event) {
  if (event.keyCode === 13) {
    document.getElementById("btnSubmit").click();
  }
});
D. Seah
  • 4,472
  • 1
  • 12
  • 20
  • This seems to have worked, but the inputted text doesn't remain appended to the list that it was added to. I am also getting the "Uncaught ReferenceError: submitIdea is not defined" error in the console log. – AelaHuntress Jul 13 '18 at 06:21
  • I am truly at a loss. The code partially works. When I mouse click and press the enter key, the submit button now captures the text, but inputs it and then seems to refresh the page at the same time, so it is like a flicker, to put it imaginatively. Also, when I use the enter key, it seems to flicker two new list elements, rather than one when I mouse click the button. – AelaHuntress Jul 13 '18 at 06:35
  • P.S. Here is my HTML:
      – AelaHuntress Jul 13 '18 at 06:38