How to autosubmit a form in javascript?

余生长醉 提交于 2019-12-01 19:58:38

Something like this would work:

<form action="#">
    <input type="" id="input" />
    <button type="submit"></button:>
</form>

<script>
function send_data() {
    document.forms[0].submit();
}

window.onload = function(){
    var input = document.getElementById('input');
    input.onchange = send_data;
}
</script>

But I'd add a few caveats:

  1. I'm assuming there is only one form on the page. You would be safer assigning and ID to your form and using getElementById and referencing that instead of document.forms[x]
  2. The change event will only happen after you lose focus on the input, which I probably what you want? Just making sure it's expected behavior
  3. Without knowing why you need to do this, I'd note that it could potentially be very annoying to the user, as submission will trigger a new page load. You may be better off doing a submission via ajax so as not to disrupt the user's browsing. If you do this, I strongly recommend a JS library to handle this.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!