Triggering submit button with Enter keypress event and mouse click

只愿长相守 提交于 2021-02-05 08:27:26

问题


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:

  • https://memorynotfound.com/dynamically-addremove-items-list-javascript/
  • Trigger a button click with JavaScript on the Enter key in a text box

回答1:


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();
  }
});



回答2:


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();
    }
});


来源:https://stackoverflow.com/questions/51318357/triggering-submit-button-with-enter-keypress-event-and-mouse-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!