使用JQuery

时间:2018-11-09 17:39:07

标签: javascript php jquery

我有一个简单的模式,当打开时,它允许用户通过JQuery单击加号图标来添加多个名称。

我目前遇到的问题是,我需要捕获输入到所有名称字段中的数据并将其格式化为JSON数组,以便可以发布数据。我可以注销第一个字段,但没有其他任何字段。下面列出了简化的代码,但完整版本可以查看here

        <div class="modal-body">
        <ul class="nav nav-tabs" id="myTab" role="tablist">
          <li class="nav-item">
            <a class="nav-link active" id="users-tab" data-toggle="tab" href="#users" role="tab" aria-controls="users" aria-selected="true">Users</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" id="groups-tab" data-toggle="tab" href="#groups" role="tab" aria-controls="groups" aria-selected="false">Groups</a>
          </li>
        </ul>
        <div class="tab-content" id="myTabContent">
          <!-- Content for the users tab -->
          <div class="tab-pane fade show active" id="users" role="tabpanel" aria-labelledby="users-tab">
            <div class="wrapper">
              <div class="users">
                <u><h6>Name</h6></u>
                <form id="input" action="modal.php" method="post">
                  <span id="name"></span>
                </form>
              </div>
              <div class="permissions">
              </div>
            </div>
          </div>
          <!-- Content for the groups tab -->
          <div class="tab-pane fade" id="groups" role="tabpanel" aria-labelledby="groups-tab">
            Group Level Permissions
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-success" id="new_rule"><i class="fas fa-plus"></i></button>
        <button type="button" class="btn btn-primary" data-dismiss="modal" data-toggle="modal" data-target="#saved" id="save">Save</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
  $(document).ready(function(){
             $("#new_rule").click(function(){
                var input = "<input type='text' name='name' placeholder='name' class='form-control' id='name_input'>";
                 $("#name").prepend(input);
             });
             $("#save").click(function(){
               var value = $("#name_input").val();
               console.log(value);
             });
         });
</script>

4 个答案:

答案 0 :(得分:0)

您可以使用serializeArray()函数序列化表单输入。这将返回一个查询字符串,然后可以将其转换为JSON.stringify()并使用添加了每个名称的数组的JSON对象。

$(document).ready(function(){
    $("#new_rule").click(function(){
        var input = "<input type='text' name='name' placeholder='name' class='form-control' id='name_input'>";
         $("#name").prepend(input);
    });
    $("#save").click(function(){
        var data = $('#input').serializeArray();
        console.log(JSON.stringify(data));
    });
});

答案 1 :(得分:0)

尝试下面的代码段。

  1. 捕获在所有名称字段中输入的数据

    var value = $("input[name='name']") .map(function() { return $(this).val(); }).get();

  2. 将其格式化为JSON数组

    var jsonStr = JSON.stringify(value);

$(document).ready(function() {
    $("#new_rule").click(function() {
        var input = "<input type='text' name='name' placeholder='name' class='form-control'>";
        $("#name").prepend(input);
    });
    $("#save").click(function() {
        var value = $("input[name='name']")
            .map(function() {
                return $(this).val();
            }).get();
        var jsonStr = JSON.stringify(value);
        console.log(jsonStr);
    });
});
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
    <title>Modal</title>
    <style media="screen">
        .wrapper>div {
            background: #eee;
            padding: 1em;
        }

        .wrapper>div:nth-child(odd) {
            background: #ddd;
        }

        .wrapper {
            display: grid;
            grid-template-columns: 70% 30%;
        }
    </style>
</head>

<body>

    <!-- Button trigger modal -->
    <div class="permissions">
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#new">
        Permissions
      </button>
    </div>

    <!-- Modal -->
    <div class="modal fade new" id="new" tabindex="-1" role="dialog" aria-labelledby="new_modal" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="permissions">Permissions</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true"><i class="fas fa-times"></i></span>
            </button>
                </div>
                <div class="modal-body">
                    <ul class="nav nav-tabs" id="myTab" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" id="users-tab" data-toggle="tab" href="#users" role="tab" aria-controls="users" aria-selected="true">Users</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" id="groups-tab" data-toggle="tab" href="#groups" role="tab" aria-controls="groups" aria-selected="false">Groups</a>
                        </li>
                    </ul>
                    <div class="tab-content" id="myTabContent">
                        <!-- Content for the users tab -->
                        <div class="tab-pane fade show active" id="users" role="tabpanel" aria-labelledby="users-tab">
                            <div class="wrapper">
                                <div class="users">
                                    <u><h6>Name</h6></u>
                                    <form id="input" action="modal.php" method="post">
                                        <span id="name"></span>
                                    </form>
                                </div>
                                <div class="permissions">
                                </div>
                            </div>
                        </div>
                        <!-- Content for the groups tab -->
                        <div class="tab-pane fade" id="groups" role="tabpanel" aria-labelledby="groups-tab">
                            Group Level Permissions
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success" id="new_rule"><i class="fas fa-plus"></i></button>
                    <button type="button" class="btn btn-primary" data-dismiss="modal" data-toggle="modal" data-target="#saved" id="save">Save</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Saved Modal -->
    <div class="modal fade" id="saved" tabindex="-1" role="dialog" aria-labelledby="saved" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLongTitle">Save Changes</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you would like to save the following changes?</p>
                    <div class="wrapper">
                        <div class="users">
                            <u><h6>Name</h6></u>
                            <span id="name"></span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">Dismiss</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->

    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>

</html>

答案 2 :(得分:0)

也许可以尝试使用此方法来获取值数组,然后对它们执行任何操作,这适用于“文本”类型的输入字段,但是您可以根据需要进行调整。该功能已分配给按钮的onClick事件。

 <script>
  var GetFieldValues = function(){
      var values=[];
      $("input[type='text']").each(function(){
          values.push($(this).val());
      });

      console.log(values);

  }

</script>

答案 3 :(得分:0)

与此您可以解决朋友:

$(document).ready(function(){
                 $("#new_rule").click(function(){
                    var input = "<input type='text' name='name[]' placeholder='name' class='form-control' id='name_input'>";
                     $("#name").prepend(input);
                 });
                 $("#save").click(function(){
                   var names = [];
                   $('input[name^="name"]').each(function() {
                        names.push($(this).val());
                   });
                   console.log(JSON.stringify(names));
                 });
             });