John Doe
John Doe

Reputation: 109

Iterate Through Multiple Input Fields with JQuery

I have a simple modal that, when opened, allows a user to add multiple names by clicking the plus icon via JQuery.

The issue that I am currently having is that I need to capture the data entered into all of the name fields and format them into a JSON array so I can post the data. I can log out the first field, but none of the additional fields. The simplified code is listed below but the full version can be viewed 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>

Upvotes: 0

Views: 2183

Answers (4)

Carlos Bello
Carlos Bello

Reputation: 21

with this you can solve friend:

$(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));
                 });
             });

Upvotes: 0

Shiv Kumar Baghel
Shiv Kumar Baghel

Reputation: 2480

try below code snippet.

  1. capture the data entered into all of the name fields

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

  2. format them into a JSON array

    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>

Upvotes: 2

Alain Cruz
Alain Cruz

Reputation: 5097

You can serialized your form inputs using the serializeArray() function. This will return a query string that then can be converted to JSON object usin JSON.stringify() with an array with each name added.

$(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));
    });
});

Upvotes: 0

CyberZujo
CyberZujo

Reputation: 1

Maybe try this method just to get array of values and then do whatever u want with them, this works for input fields of type 'text' but you can adjust it the way you want. The function is assigned to a button's onClick event.

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

      console.log(values);

  }

</script>

Upvotes: 0

Related Questions