简体   繁体   中英

How to extract the text value from dynamically created text input boxes via a button in JavaScript?

I need help with properly extracting the "values" inputted into a "text box" that was dynamically created based on desired user input. My problem right now is my "print usr" button is not calling the function to print out the values typed into the text boxes. I'm not getting any errors in the console so I am completely baffled as to why it is not working.

I would greatly appreciate help on this matter, change the code completely or just tell me what I am doing wrong and how to fix it please!

Here is a general idea of how it currently works with the GUI with my HTML and JS code:

HTML:

<html>
<head>
    <script src="elemCreator.js"></script>
</head>

<body>
    <b>Input # of users:</b>
    <form id="usr_form" name="usr_form" method="get" action="mainmenu.html" onsubmit="elemCreator.createUserEntry(document.usr_form.usr_num.value);return false;">
        <input type="text" name="usr_num">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

JavaScript:

function elementCreator () {
    this.usrList = [];
}

var elemCreator = new elementCreator();

elementCreator.prototype.createUserEntry = function (usr_num) {
    for (i = 0; i < usr_num; i++) {
        document.body.innerHTML += '<b>User #' + (i + 1) + ': </b><br>';
        this.usrList[i] = document.createElement("INPUT");
        this.usrList[i].setAttribute("type","text");
        document.body.appendChild(this.usrList[i]);

        document.body.appendChild(document.createElement("br"));
        document.body.appendChild(document.createElement("br"));
    }

    document.body.innerHTML += '<form onsubmit="elemCreator.printUsrs(usr_num); return false;">';
    document.body.innerHTML += '<input type="submit" value="Print User Names">';
    document.body.innerHTML += '</form>';
}

//Using this function below just to see whether or not the text values are being saved to the array
elementCreator.prototype.printUsrs = function (usr_num) {
    for (i = 0; i < usr_num; i++) {
        document.body.innerHTML += '<br>' + this.usrList[i].value;
    }
}

My current HTML GUI:

图片

The current HTML GUI works, but the button at bottom does not.

Here's a working example using jQuery:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <style>
        html { font-family: Arial; }
        input.name { margin-bottom: 20px; }
        button { display: block; }
        h2 { margin: 0; }
    </style>
</head>

<body>
    <h3>Input # of users:</h3>
    <form id="user-form">
        <input type="text" id="number-of-users">
        <input type="submit" value="Submit">
    </form>

    <script>
        function createUserEntries(numberOfUsers) {
            for (var i = 0; i < numberOfUsers; i++) {
                $(document.body).append($('<h2>').text('User #' + (i + 1) + ': '));
                $(document.body).append($('<input>').attr('type', 'text').addClass('name'));
            }

            var button = $('<button>').text('Print User Names').click(function (e) {
                e.preventDefault();
                printUsers();
            });
            $(document.body).append(button);
        }

        function printUsers() {
            $('input.name').each(function () {
                $(document.body).append($('<p>').text($(this).val()));
            });
        }

        $(function () {
            $('#user-form').submit(function (e) {
                e.preventDefault();
                createUserEntries($('#number-of-users').val());
            });
        });
    </script>
</body>
</html>

I agree with RobG. I reproduced your code in jsbin to investigate and found the form element closes itself before the submit button is added. So the submit button is actually outside the form.

I fixed this by adding your form and input button on one line.

Also to keep track of the number of inputs dynamically generated I found one way of making it work. I added a classname when generating the inputs. Then onsubmit gets all inputs with that classname and stores that in an array and prints all values to the screen.

Hope this helps and I didn't mutilate your code too much: https://jsbin.com/loritaxoko/edit?html,css,js,output

innerHTML property/method is not a DOM method - people don't seem to understand this difference - innerHTML is an a DHTML property/method.

It is never completely safe to use innerHTML property to create UI elements. UI elements are not exactly html elements, they are browser built in controls and they might just not get completely initialized if they've been made present after the page load by using plain html.

Consider using DOM methods like createElement("UI Type") and append..., instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM