如何通过JavaScript中的按钮从动态创建的文本输入框中提取文本值?

时间:2022-10-22 07:44:28

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.

我需要帮助正确提取输入到“文本框”中的“值”,该“文本框”是基于所需的用户输入动态创建的。我现在的问题是我的“print usr”按钮没有调用函数来打印输出到文本框中的值。我没有在控制台中出现任何错误,所以我完全不知道为什么它不起作用。

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和JS代码一起使用GUI的一般概念:

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:

我目前的HTML GUI:

如何通过JavaScript中的按钮从动态创建的文本输入框中提取文本值?

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

当前的HTML GUI可以工作,但底部的按钮却不行。

3 个解决方案

#1


0  

Here's a working example using jQuery:

这是一个使用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>

#2


0  

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.

我同意RobG。我在jsbin中重现了你的代码以进行调查,发现在添加提交按钮之前,表单元素会自行关闭。所以提交按钮实际上在表单之外。

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.

另外,为了跟踪动态生成的输入数量,我发现了一种使其工作的方法。我在生成输入时添加了一个类名。然后onsubmit获取具有该类名的所有输入并将其存储在数组中并将所有值输出到屏幕。

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

希望这有帮助,我没有过多地破坏你的代码:https://jsbin.com/loritaxoko/edit?html,css,js,output

#3


0  

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

innerHTML属性/方法不是DOM方法 - 人们似乎不理解这种差异 - innerHTML是一个DHTML属性/方法。

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.

使用innerHTML属性创建UI元素绝不是完全安全的。 UI元素不完全是html元素,它们是浏览器内置的控件,如果在页面加载后使用普通的html使它们存在,它们可能就不会完全初始化。

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

考虑使用DOM方法,如createElement(“UI Type”)和append ...,而不是。

#1


0  

Here's a working example using jQuery:

这是一个使用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>

#2


0  

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.

我同意RobG。我在jsbin中重现了你的代码以进行调查,发现在添加提交按钮之前,表单元素会自行关闭。所以提交按钮实际上在表单之外。

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.

另外,为了跟踪动态生成的输入数量,我发现了一种使其工作的方法。我在生成输入时添加了一个类名。然后onsubmit获取具有该类名的所有输入并将其存储在数组中并将所有值输出到屏幕。

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

希望这有帮助,我没有过多地破坏你的代码:https://jsbin.com/loritaxoko/edit?html,css,js,output

#3


0  

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

innerHTML属性/方法不是DOM方法 - 人们似乎不理解这种差异 - innerHTML是一个DHTML属性/方法。

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.

使用innerHTML属性创建UI元素绝不是完全安全的。 UI元素不完全是html元素,它们是浏览器内置的控件,如果在页面加载后使用普通的html使它们存在,它们可能就不会完全初始化。

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

考虑使用DOM方法,如createElement(“UI Type”)和append ...,而不是。