JavaScript获取input输入框值返回undefined问题求助
问题分析与解决
你的代码出现undefined的原因有两个核心问题:
- 页面刚加载就执行了
getElementById('lname').value和getElementById('fname').value,这时候输入框是空的,而且后续用户输入内容后,这两个const变量不会自动更新——因为它们只在初始化时赋值了一次。 - 点击按钮调用
submit()时没有传参数,同时submit函数的形参lname、fname会覆盖外部的同名变量,导致函数内部拿到的是未定义的形参值。
修正后的代码
<form> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname" ><br> <label for="lname">Last name:</label><br> <input type="text" id="lname" name="lname"> <button type="button" id="butt">click here </button> </form> <script> document.getElementById('butt').onclick = function() { // 点击时才获取当前输入框的最新值 const lname = document.getElementById('lname').value; const fname = document.getElementById('fname').value; submit(lname, fname); } function submit(lname, fname){ alert(lname); console.log(fname); } </script>
也可以用更简洁的写法,直接在函数内部获取值,避免参数传递的问题:
<form> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname" ><br> <label for="lname">Last name:</label><br> <input type="text" id="lname" name="lname"> <button type="button" id="butt">click here </button> </form> <script> document.getElementById('butt').onclick = submit; function submit(){ const lname = document.getElementById('lname').value; const fname = document.getElementById('fname').value; alert(lname); console.log(fname); } </script>
关键修正点
- 延迟获取值:把获取输入框值的操作移到点击事件触发时执行,这样每次点击都能拿到用户当前输入的最新内容。
- 避免变量覆盖:要么确保调用函数时传入正确参数,要么直接在函数内部获取值,杜绝形参覆盖外部变量的情况。
内容的提问来源于stack exchange,提问作者xcrystal360
相关产品推荐
相关产品推荐

