gpt4 book ai didi

javascript - 使用 JavaScript 获取表单中输入字段的值

转载 作者:行者123 更新时间:2023-12-01 03:54:53 26 4
gpt4 key购买 nike

有人可以帮助我理解为什么如果我将输入字段包装在表单字段中,控制台日志无法打印该值吗?

HTML:

  <form>
<input id="formEntry" type="text">
<button id="btn-3">Add Custom Line</button>
</form>

JavaScript:

 var addCustomLine = function(){
var customLine = document.getElementById("formEntry").value;
console.log(customLine);
}

document.getElementById("btn-3").addEventListener ("click", addCustomLine, false);

最佳答案

通过不指定按钮类型,它默认提交父表单。您可以通过将类型显式设置为“按钮”来防止此行为。

<button type="button" id="btn-3">Add Custom Line</button>

关于javascript - 使用 JavaScript 获取表单中输入字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42846488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com