javascript - 从控制台使用 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中的函数。
解决方案
尝试隐藏输入按钮。
<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>
我希望它有所帮助。
推荐阅读
- docker - sudo:找不到命令| gitlab-ci
- python-3.x - Unable to plot bubble plot with right size
- reactjs - 如何在 React Native 中的自定义视图上将道具传递给 StyleSheet?
- c++ - 跨平台库究竟如何适用于不同的机器
- python - How to do Categorical in pandas
- python - Is this a circular import?
- c# - I have an issue with a contact form. Works on localhost. When deployed its giving error when attempting to post it via the submit button
- java - Make recursive API call using Retrofit
- javascript - Reactjs 变量在 useEffect 之后返回未定义
- python - 如何显示图像并在 1.5 秒后将其杀死?