javascript 使用 jQuery 动态创建选择框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19131040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:29:47  来源:igfitidea点击:

Create select box dynamically with jQuery

javascriptphpjqueryhtmlforms

提问by dev1234

i am creating a dynamic dropdowns based on a scenario i need to. i am wondering how it possible to keep the states of those added drop downs dynamically when a page is loading after submit button is clicked.

我正在根据我需要的场景创建动态下拉列表。我想知道如何在单击提交按钮后加载页面时动态保持那些添加的下拉列表的状态。

i am able to stote a variable in jquery and check whether form is submitted or not and if submitted to load back the previously dynamically added dropdowns (html select box) but even though i load them back still i have a problem of getting the previously selected values of those dynamic dropdowns.

我能够在 jquery 中存储一个变量并检查表单是否已提交以及是否提交以加载回以前动态添加的下拉列表(html 选择框),但即使我将它们加载回来,我仍然遇到获取先前选择的问题这些动态下拉列表的值。

I have created a fiddler. http://jsfiddle.net/jBJSw/8/

我创建了一个小提琴手。http://jsfiddle.net/jBJSw/8/

My form

我的表格

<form>
    <div id="TextBoxesGroup">
        <div id="TextBoxDiv1">
            <label>Textbox #1 :</label>
            <input type="text" id="textbox1">
        </div>
    </div>
    <input type="button" value="Add Button" id="addButton">
    <input type="submit" value="submit Button" id="subButton">
</form>

Script

脚本

  $(document).ready(function () {

      var counter = 2;

      $("#addButton").click(function () {

          if (counter > 10) {
              alert("Only 10 allow");
              return false;
          }

          var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
          newTextBoxDiv.after().html('<label>Select #' + counter + ' : </label>' +
              '<select id="select' + counter + '" ><option value="' + "val" + ' ">"' + "desc2" + '"</option><option value="' + "val2" + ' ">"' + "desc" + '"</option><option value="' + "val3" + ' ">"' + "desc3" + '"</option>');

          newTextBoxDiv.appendTo("#TextBoxesGroup");
          counter++;
      });
  });

Appreciate if any help on finding a way to get the previously selected values after form submission. (this is needed because when a form is submitted with errors, these selected values should be same but now it refreshes and comes to default. also in a view scenario also this should be preloaded)

感谢在表单提交后找到获取先前选择的值的方法的任何帮助。(这是必需的,因为当提交的表单有错误时,这些选定的值应该是相同的,但现在它会刷新并成为默认值。同样在视图场景中,这也应该被预加载)

采纳答案by Drixson Ose?a

Sorry for getting late have trouble in my work. Here's a possible solution for your problem.

抱歉迟到了,工作上有问题。这是您的问题的可能解决方案。

DOM:

DOM:

<form id="myform" method="post"> <!--adding id attribute-->
    <div id="TextBoxesGroup">
        <div id="TextBoxDiv1">
            <label>Textbox #1 :</label>
            <input type="text" id="textbox1">
        </div>

        <!--check if POST is established-->
        <?php if($_POST): ?>
            <?php if(count($_POST['mySelect']) < 0 ): ?>

            <?php

               //Recreate your select DOM
               $arr = $_POST['mySelect'];
               foreach($arr as $ind => $val){

                  echo '<select>';
                  echo '<option val="val" ' . ($val == "val" ? "selected" : "") . '>desc2</option>';
                  echo '<option val="val2" ' . ($val == "val2" ? "selected" : "") . '>desc</option>';
                  echo '<option val="val3" ' . ($val == "val3" ? "selected" : "") . '>desc3</option>';
                  echo '</select>';
               }

            ?>                


            <?php endif; ?>
        <?php endif; ?>
    </div>
    <input type="button" value="Add Button" id="addButton">
    <input type="submit" value="submit Button" id="subButton">
</form>

SCRIPT:

脚本:

 $(document).ready(function () {

      var counter = 2;

      $("#addButton").click(function () {

          if (counter > 10) {
              alert("Only 10 allow");
              return false;
          }

          var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
          newTextBoxDiv.after().html('<label>Select #' + counter + ' : </label>' +
              '<select id="select' + counter + '" ><option value="' + "val" + ' ">"' + "desc2" + '"</option><option value="' + "val2" + ' ">"' + "desc" + '"</option><option value="' + "val3" + ' ">"' + "desc3" + '"</option>');

          newTextBoxDiv.appendTo("#TextBoxesGroup");
          counter++;
      });

     //adding hidden inputs
     $('#myFORM').on('submit', function(){

      $('#myFORM select').each(function(){
         slct = $('<input type="hidden" name="mySelect[]" value="' +  $(this).val() +'">');
         $('#myFORM').append(slct);
      });

  });
  });

回答by Raab

You will have to send back the selected value to the page from server side in the querystring or post header. then select the option accordingly in jquery on the base of the the value sent back.

您必须在查询字符串或帖子标头中将所选值从服务器端发送回页面。然后根据发回的值在 jquery 中相应地选择选项。