代码之家  ›  专栏  ›  技术社区  ›  stickynotememo

为什么从javascript中输入的表单中检索到的值返回空值或null值?

  •  0
  • stickynotememo  · 技术社区  · 1 年前

    记录问题变量会返回下拉列表中选择的选项,但记录深度变量不会返回任何结果。

        <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><br>
                    <option value="even_fibonacci.php">Even fibonacci numbers</option><br>
                </select>
                
                <label for="depth_input">Depth</label>
                <input id="depth_input" class="form-control" name="depth_input">test</input>
                <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>
                
                let problem = document.getElementById("problem_selector").value;
                let depth   = document.getElementById("depth_input").value;
                const button = document.getElementById("submit_button");
                button.addEventListener('click', function() {
                    console.log(depth); 
                    console.log(problem);
                });
            </script>
    

    enter image description here 单击提交按钮时拍摄的屏幕截图。 按下按钮后,应将深度值与问题值一起记录。

    我已经将提交按钮更改为输入按钮,但这似乎没有帮助。以前返回的值为null;但现在这个值只是空的。

    1 回复  |  直到 1 年前
        1
  •  1
  •   Matthew Herbst    1 年前

    读取按钮值的代码正在运行 立即 页面加载时。单击按钮后,您需要读取值:

      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);
    });