HTML表单提交后将输入框值展示至外部min2输入框的实现问题
解决表单提交后将输入值同步到外部输入框的问题
你的需求是把表单内userInput3输入框的值,在表单提交后同步到表单外的min2只读输入框里。现有代码存在几个问题,下面是修正后的完整代码及说明:
修正后的HTML
<form class="searchform"> <input name="Input.minp" id="Input.price.min" asp-for="Input.minp" /> <input id="userInput3" placeholder="min" style="height :30px;width:90px; border-style:solid ;border-color: black;border-radius:5px; margin-left:20px;margin-top:5px;"> <button type="submit" class="searchButton" id="searchButton">submit</button> </form> <input id="min2" style="height :30px;width:70px; border:none;outline:none; margin-left:30px;" readonly>
修正后的JavaScript
<script> const num3rs = val => val.toLocaleString('en-IN', { maximumFractionDigits: 0 }); // 输入时格式化数字并同步到min1(注意:HTML里未找到min1元素,需自行确认是否存在) document.getElementById("userInput3").addEventListener("input", function () { const cleanValue = +this.value.replace(/\D/g, ""); this.value = num3rs(cleanValue); const min1El = document.getElementById("min1"); if (min1El) min1El.value = this.value; }); // 表单提交处理 $(".searchform").submit(function(e) { // 阻止表单默认提交行为(避免页面刷新导致赋值失效) e.preventDefault(); // 获取userInput3的输入值 const inputValue = document.getElementById('userInput3').value; // 将值同步到min2输入框 document.getElementById('min2').value = inputValue; // 若需实际提交表单数据,可在此添加AJAX请求 // 示例: // $.ajax({ // url: this.action, // method: this.method, // data: $(this).serialize(), // success: function(res) { // // 提交成功后的后续处理 // } // }); }); </script>
关键修正点说明
- jQuery选择器修正:原代码
$("searchform")未正确识别类选择器,需改为$(".searchform")才能选中目标表单。 - 阻止默认提交行为:表单默认提交会刷新页面,导致
min2的赋值被重置,必须用e.preventDefault()拦截默认行为;若需提交数据,改用AJAX方式。 - 取值逻辑修正:submit事件中
this指向表单元素,表单无value属性,需直接获取userInput3的value值。 - 容错处理:针对
min1元素可能不存在的情况,添加存在性判断避免控制台报错。
内容的提问来源于stack exchange,提问作者Qasim Asghar
相关产品推荐
相关产品推荐

