简体   繁体   English

将来自动态生成的文本框的值存储到数组中

[英]Store values from dynamically generated text boxes into array

I'm creating a Time table generating website as a part of my project and I am stuck at one point. 我正在创建一个时间表生成网站,这是我的项目的一部分,但我停留在一个地方。

Using for loop, I am generating user selected text boxes for subjects and faculties. 使用for循环,我正在为用户和学科生成用户选择的文本框。 Now the problem is that I cannot get the values of those dynamically generated text boxes. 现在的问题是,我无法获取那些动态生成的文本框的值。 I want to get the values and store it into array so that I can then later on store it to database 我想获取值并将其存储到数组中,以便以后可以将其存储到数据库中

If I am using localstorage, then it sometimes shows NaN or undefined. 如果我使用的是localstorage,则有时会显示NaN或未定义。 Please help me out. 请帮帮我。

Following is my Jquery code 以下是我的jQuery代码

$.fn.CreateDynamicTextBoxes = function()
        {
            $('#DynamicTextBoxContainer, #DynamicTextBoxContainer2').css('display','block');

            InputtedValue = $('#SemesterSubjectsSelection').val();

            SubjectsNames = [];

            for (i = 0; i < InputtedValue; i++)
            {
                TextBoxContainer1 = $('#DynamicTextBoxContainer');
                TextBoxContainer2 = $('#DynamicTextBoxContainer2');

                $('<input type="text" class="InputBoxes" id="SubjectTextBoxes'+i+'" placeholder="Subject '+i+' Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer1);
                $('<input type="text" class="InputBoxes" id="FacultyTextBoxes'+i+'" placeholder="Subject '+i+' Faculty Name" style="margin:5px;" value=""><br>').appendTo(TextBoxContainer2);
                SubjectsNames['SubjectTextBoxes'+i];
            }

            $('#DynamicTextBoxContainer, #UnusedContainer, #DynamicTextBoxContainer2').css('border-top','1px solid #DDD');
        }

        $.fn.CreateTimeTable = function()
        {
            for (x = 0; x < i; x++)
            {
                localStorage.setItem("Main"+x, +SubjectsNames[i]);
            }
        }

I am also posting screenshot for better understanding 我也在发布屏幕截图,以更好地理解

在此处输入图片说明

I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. 我了解您为每个科目创建2个文本框,一个为科目创建,第二个为教职员工。 And you want it as a jQuery plugin. 而您希望它作为jQuery插件。

First of all, I think you should create single plugin instead of two, and expose what you need from the plugin. 首先,我认为您应该创建单个插件而不是两个,并从插件中公开您的需求。

You should avoid global variables, right now you have InputtedValue , i , SubjectsNames , etc. declared as a global variables, and I believe you should not do that, but keep these variables inside you plugin and expose only what you really need. 您应该避免使用全局变量,现在您已经将InputtedValueiSubjectsNames等声明为全局变量,并且我相信您不应该这样做,而是将这些变量保留在插件内并仅公开真正需要的内容。

You declare your SubjectNames , but later in first for loop you try to access its properties, and actually do nothing with this. 您声明了SubjectNames ,但是稍后在第一个for循环中,您尝试访问其属性,并且对此实际上不执行任何操作。 In second for loop you try to access it as an array, but it's empty, as you did not assign any values in it. 在第二个for循环中,您尝试将其作为数组访问,但是它为空,因为您没有在其中分配任何值。

Take a look at the snippet I created. 看看我创建的代码段。 I do not play much with jQuery, and especially with custom plugins, so the code is not perfect and can be optimized, but I believe it shows the idea. 我在jQuery方面玩的不多,尤其是在使用自定义插件方面,所以代码不是完美的并且可以优化,但是我相信它可以说明这一点。 I pass some selectors as in configuration object to make it more reusable. 我在配置对象中传递了一些选择器,以使其更可重用。 I added 2 buttons to make it more "playable", but you can change it as you prefer. 我添加了2个按钮以使其更“可玩”,但是您可以根据自己的喜好进行更改。 Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result div. “准备”按钮创建动态文本框,“ 生成 ”按钮获取它们的值并在结果div中“打印”它们。 generate method is exposed from the plugin to take the values outside the plugin, so you can do it whatever you want with them (eg store them in local storage). 插件公开了generate方法以将值带到插件之外,因此您可以随便使用它们(例如将它们存储在本地存储中)。

 $(function() { $.fn.timeTables = function(config) { // prepare variables with jQuery objects, based on selectors provided in config object var numberOfSubjectsTextBox = $(config.numberOfSubjects); var subjectsDiv = $(config.subjects); var facultiesDiv = $(config.faculties); var prepareButton = $(config.prepareButton); var numberOfSubjects = 0; prepareButton.click(function() { // read number of subjects from the textbox - some validation should be added here numberOfSubjects = +numberOfSubjectsTextBox.val(); // clear subjects and faculties div from any text boxes there subjectsDiv.empty(); facultiesDiv.empty(); // create new text boxes for each subject and append them to proper div // TODO: these inputs could be stored in arrays and used later for (var i = 0; i < numberOfSubjects; i++) { $('<input type="text" placeholder="Subject ' + i + '" />').appendTo(subjectsDiv); $('<input type="text" placeholder="Faculty ' + i + '" />').appendTo(facultiesDiv); } }); function generate() { // prepare result array var result = []; // get all text boxes from subjects and faculties divs var subjectTextBoxes = subjectsDiv.find('input'); var facultiesTextBoxes = facultiesDiv.find('input'); // read subject and faculty for each subject - numberOfSubjects variable stores proper value for (var i = 0; i < numberOfSubjects; i++) { result.push({ subject: $(subjectTextBoxes[i]).val(), faculty: $(facultiesTextBoxes[i]).val() }); } return result; } // expose generate function outside the plugin return { generate: generate }; }; var tt = $('#container').timeTables({ numberOfSubjects: '#numberOfSubjects', subjects: '#subjects', faculties: '#faculties', prepareButton: '#prepare' }); $('#generate').click(function() { // generate result and 'print' it to result div var times = tt.generate(); var result = $('#result'); result.empty(); for (var i = 0; i < times.length; i++) { $('<div>' + times[i].subject + ': ' + times[i].faculty + '</div>').appendTo(result); } }); }); 
 #content div { float: left; } #content div input { display: block; } #footer { clear: both; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container"> <div id="header"> <input type="text" id="numberOfSubjects" placeholder="Number of subjects" /> <button id="prepare"> Prepare </button> </div> <div id="content"> <div id="subjects"> </div> <div id="faculties"> </div> </div> </div> <div id="footer"> <button id="generate">Generate</button> <div id="result"> </div> </div> 

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

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