Submit Event Listener for a form

放肆的年华 提交于 2019-12-19 08:04:07

问题


I've written an event listener for a form submit that is causing me a few issues. When pressing 'enter' inside the text field everything works fine. However, I have an span (with background-image) that submits the form as well via a click event. This is not working properly and I can't figure out why.

Here's the basic HTML:

<form name="myForm">
  <input type="text" name="search" />
  <span id="search-button"></span>
</form>

Here's the JS for the event listener:

function evtSubmit(e) {
  // code
  e.preventDefault();
};

var myform = document.myForm;
if (myform.addEventListener) {
  myform.addEventListener('submit', evtSubmit, false);
}

And here's the JS for the 'span' and its click event:

var searchButton = document.getElementById('search-button');
if (searchButton) {
 searchButton.onclick = function() {
  document.myForm.submit();
 };
}

NOTE: The JS for the span's click event is in a separate JS file and inaccessible atm, so changing that script is less of an option. If the only way to fix this issue is to update that file, I can...but due to processes beyond my control, it's much more difficult.


回答1:


When calling form.submit(), the onsubmit event won't be triggered. As an alternative, you can set the action attribute to javascript:evtSubmit(event):

function evtSubmit(e) {
  // code
  e.preventDefault();
};

var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');


来源:https://stackoverflow.com/questions/3841298/submit-event-listener-for-a-form

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