简体   繁体   English

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

[英]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. 我现在的问题是我的“打印usr”按钮没有调用函数以打印出键入文本框中的值。 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和JS代码与GUI配合使用的一般思路:

HTML: 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: 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:

图片

The current HTML GUI works, but the button at bottom does not. 当前的HTML GUI有效,但底部的按钮无效。

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>

I agree with RobG. 我同意RobG。 I reproduced your code in jsbin to investigate and found the form element closes itself before the submit button is added. 我在jsbin中复制了您的代码以进行调查,并发现在添加提交按钮之前,表单元素会自行关闭。 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. 然后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

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. 使用innerHTML属性创建UI元素从来都不是完全安全的。 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. UI元素并非完全是html元素,它们是浏览器内置的控件,如果使用纯HTML在页面加载后将它们显示出来,则它们可能只是未完全初始化。

Consider using DOM methods like createElement("UI Type") and append..., instead. 考虑使用DOM方法,例如createElement(“ UI Type”)和append...。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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