You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript表单输入值获取为空/Null问题求助

表单取值为空/Null问题解决

问题根源

你的代码存在两个关键问题:

  • input标签格式错误:<input>是自闭合标签,不能在标签内部写入内容(比如test),浏览器无法正确解析这种写法,会导致初始值无法被识别,进而取值为空。
  • 取值时机错误:你在页面加载时就获取了problem和depth的值,此时用户还未对表单进行任何操作,点击按钮时打印的是页面加载时的旧值,而非用户修改后的最新值。

修复方案

  1. 修正input标签写法,将默认值通过value属性设置:
    <input id="depth_input" class="form-control" name="depth_input" value="test">
    
  2. 将取值逻辑移到按钮点击事件的回调函数内部,确保每次点击时获取最新的表单值。

修改后的完整代码

<body>
    <form class="card p-4" method="POST" id="form">
        <label for="problem_selector">Problem</label>
        <select id="problem_selector" class="form-control" name="problem_name">
            <option value="3and5multiples.php">Multiples of 3 and 5</option>
            <option value="even_fibonacci.php">Even fibonacci numbers</option>
        </select>
        
        <label for="depth_input">Depth</label>
        <input id="depth_input" class="form-control" name="depth_input" value="test">
        <input id="submit_button" value="submit" type="button" class="btn btn-primary"/>
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script>
        const button = document.getElementById("submit_button");
        button.addEventListener('click', function() {
            // 点击时才获取最新值
            let problem = document.getElementById("problem_selector").value;
            let depth   = document.getElementById("depth_input").value;
            console.log(depth); 
            console.log(problem);
        });
    </script>
</body>

额外说明

<select>标签里的<br>标签是多余的,<option>本身就是块级展示,不需要额外换行,已在修正后的代码中移除。

内容的提问来源于stack exchange,提问作者mkfifo_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 15:02:32