首页 > 解决方案 > 从控制台使用 javascript 填写和提交表单

问题描述

这是我的表格:

 <form id="myForm">
        <input id="htmlString" type="text" name="htmlField" ><br>
        <input type="Submit" value="Submit" >
      </form> 

并且需要从控制台填充它。只是为了在我的应用程序中使用它,将带有数据的 javascript 注入本地 html 文件。

我试图制作没有提交按钮的表单,如下所示:

<body>

    <form id="myForm">
        <input id="htmlString" type="text" name="htmlField" ><br>
    </form> 

    <script>
        htmlString.oninput = function(){
         ///do some stuff 
        }

</script>

</body>

期待:

document.getElementById('htmlString').value="moo" ;

它自动提交表单,因为这里oninput用到了。但它只是充满了输入,并没有进一步进行。

尝试使用其他解决方案:

form = document.getElementById("myForm")
form.submit()

但它只是刷新了页面并没有提交表单。

需要的只是一个没有别的文件,并用javascript将我的字符串注入它以运行嵌入在html中的函数。

标签: javascripthtml

解决方案


尝试隐藏输入按钮。

<body>

    <form id="myForm">
        <input id="htmlString" type="text" name="htmlField" ><br>
        <input type="Submit" value="Submit" style="display: none" >
    </form>
    <button onclick="simulateConsole()">Try it</button>

    <script>
        htmlString.oninput = function(){
          if(this.value === "moo") {
             myForm.submit();
          }
        }

        // This event will be triggered even if you use console
        htmlString.onsubmit = function(){
          if(this.value === "moo") {
           // do something onSubmit
          }
        }

        function simulateConsole() {
          // you can simulate this in console
          htmlString.value = "moo";
          myForm.submit();
        }

    </script>

</body>

我希望它有所帮助。


推荐阅读