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

时间:2022-11-29 20:55:35

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. 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

使用for循环,我正在为主题和院系生成用户选择的文本框。现在的问题是我无法获取那些动态生成的文本框的值。我想获取值并将其存储到数组中,以便稍后我可以将其存储到数据库中

If I am using localstorage, then it sometimes shows NaN or undefined. Please help me out.

如果我使用的是localstorage,那么它有时会显示NaN或undefined。请帮帮我。

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

我也发布截图以便更好地理解

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

1 个解决方案

#1


0  

I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. And you want it as a jQuery plugin.

我知道你为每个主题创建了2个文本框,一个用于主题,第二个用于教师。你想要它作为一个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.

你应该避免使用全局变量,现在你将InputtedValue,i,SubjectsNames等声明为全局变量,我相信你不应该这样做,但是将这些变量保存在你的插件中并只公开你真正需要的东西。

You declare your SubjectNames, but later in first for loop you try to access its properties, and actually do nothing with this. 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.

您声明了您的SubjectNames,但稍后在第一个for循环中,您尝试访问其属性,并且实际上对此无效。在第二个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. 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. Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result 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 (e.g. store them in local storage).

看看我创建的代码片段。我没有玩jQuery,特别是使用自定义插件,所以代码并不完美,可以优化,但我相信它显示了这个想法。我在配置对象中传递了一些选择器,使其更具可重用性。我添加了2个按钮,使其更“可玩”,但您可以根据需要更改它。 “准备”按钮创建动态文本框,“生成”按钮获取其值并在结果div中“打印”它们。从插件中公开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>

#1


0  

I understand you create 2 text boxes for each subject, one for subject, and second one for faculty. And you want it as a jQuery plugin.

我知道你为每个主题创建了2个文本框,一个用于主题,第二个用于教师。你想要它作为一个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.

你应该避免使用全局变量,现在你将InputtedValue,i,SubjectsNames等声明为全局变量,我相信你不应该这样做,但是将这些变量保存在你的插件中并只公开你真正需要的东西。

You declare your SubjectNames, but later in first for loop you try to access its properties, and actually do nothing with this. 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.

您声明了您的SubjectNames,但稍后在第一个for循环中,您尝试访问其属性,并且实际上对此无效。在第二个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. 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. Prepare button creates your dynamic text boxes, and button Generate takes their values and "print" them in result 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 (e.g. store them in local storage).

看看我创建的代码片段。我没有玩jQuery,特别是使用自定义插件,所以代码并不完美,可以优化,但我相信它显示了这个想法。我在配置对象中传递了一些选择器,使其更具可重用性。我添加了2个按钮,使其更“可玩”,但您可以根据需要更改它。 “准备”按钮创建动态文本框,“生成”按钮获取其值并在结果div中“打印”它们。从插件中公开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>