点击按钮提交输入框内容至div时页面刷新导致内容丢失求助
解决输入文本显示到div并阻止页面刷新的问题
你的代码有两个核心问题:
- 按钮在
<form>标签内,默认是提交按钮,点击会触发表单提交导致页面刷新,之前的内容自然会被清空 addnewSN函数直接把传入的id字符串拼接到div里,没有获取输入框的实际输入内容
修改后的完整代码:
HTML部分:
<form> <div> <input name="snfield" type="text" id="snfield" value="any text" maxlength="20" minlength="1" required> <!-- 把按钮类型设为button,避免触发表单提交 --> <button type="button" onclick="addnewSN('snfield')"> <label id="labelsn" for="snfield">Enter Serialnumber</label> </button> </div> </form> <div id="sn"></div>
JS部分:
function addnewSN(inputId) { // 通过id获取输入框元素,提取实际输入值 const inputValue = document.getElementById(inputId).value; // 将值追加到目标div中,<br>用于换行显示,可按需移除 document.getElementById('sn').innerHTML += inputValue + '<br>'; }
另一种阻止刷新的方式:
如果不想修改按钮类型,也可以在点击事件里阻止默认提交行为,把按钮的onclick改为:
onclick="addnewSN('snfield'); return false;"
内容的提问来源于stack exchange,提问作者hanlok
相关产品推荐
相关产品推荐

