Search code examples
javascripthtmltwitter-bootstrap

Why is the value retrieved from a form input in javascript returning empty or null values?


Logging the problem variable returns the option selected in the dropdown, but logging the depth variable returns nothing.

    <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 Screenshot taken on clicking the submit button. The depth value should be logged along with the problem value once the button is pressed.

I've already changed the submit button to an input button, but that doesn't seem to have helped. Previously the value returned was null; but now the value is just empty.


Solution

  • Your code that reads the value of the buttons is running immediately on page load. You need to read the values after the button is clicked:

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