Robert junior Robert junior - 4 months ago 9
Ajax Question

Can't get the value of HTML select in AJAX response

There are two steps on my code. First step a user fills some fields and then data is submitted by ajax to server. Ajax returns a HTML select input that user must choose a value. This is the second step.

The problem is, when I try to get the value of select in javascript, it shows me null.

The code I use to get select value works in normal situation. But when select is retrieved by ajax, this problem occurs.

Code to get select value

var e = document.getElementById("ordernum");
var num = e.options[e.selectedIndex].value;

Answer

Here's an example HTML file showing how to dynamically generate a select element and get the value back from it on its onchange event via event.target.value:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script>
            const GameDifficulty = {
                EASY:1,
                MEDIUM:2,
                HARD:3,
                INSANE:4
            };

            function init(event) {
                console.log(event);
                var body = document.getElementById('body');
                var select = document.createElement('select');
                select.id = 'selDifficulty';
                for (var diff in GameDifficulty) {
                    var option = document.createElement('option');
                    option.value = GameDifficulty[diff];
                    option.innerHTML = diff;
                    select.appendChild(option);
                }

                select.onchange = test;

                body.appendChild(select);
                console.log(body);
            }

            function test(event) {
                console.log(event.target.value);
            }

            window.onload = init;
        </script>
    </head>
    <body id="body">
    </body>
</html>
Comments