我正在编写一个 JavaScript 程序,一旦单击提交按钮,该程序应该更改文本字段的文本
<script>
function change()
{
document.getElementById("set").value="helloworld";
}
</script>
文本字段和提交按钮:
<form>
Enter Text <input type="text" id="set" >
<input type="submit" value="Press here" onclick="change()" />
</form>
一旦我按下提交,它只显示一个空的文本字段。但是当我删除“表单”时,它会显示正确的结果。谁能解释一下为什么?
同样,任何人都可以解释为什么“形式”很重要,因为我们不需要它也可以收集数据。
提前致谢...
最佳答案
单击提交
按钮后,表单将被提交,因此页面将被卸载。
阻止表单提交。
function change(e) {
e.preventDefault();
//^^^^^^^^^^^^^^^^^^
document.getElementById("set").value = "helloworld";
}
<form>
Enter Text <input type="text" id="set">
<input type="submit" value="Press here" onclick="change(event)" />
</form>
关于javascript - 无法更改 JavaScript 中的文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43602475/