Illep Illep - 3 months ago 11
Ajax Question

Extract values from a div and save it in an array - JSFindle given

When a user clicks on the

add a row
button, a pair of text fields namely
username
and
password
will appear as shown in the jsfiddle link below.

Now, when the user submits the form by clicking on the
send
button, I want to extract the username and password pairs and save it in an array (as key-value pairs). So that, 1 array can have one or many pairs of username-password objects saved.

How can I do this. My working so far can be found in the jsfiddle here.

Note: I already know how to save the username and password in to an array:

var dict = {};

dict['username'] = "password";

Answer

When you create the new elements by cloning you forget to change the id because they must be unique. Moreover, you forget to reset the values.

If you add the id to password field you may address the problem like in the following snippet:

$(document).ready(function() {
  var counter = 1;
  $("#btn").click(function() {
    counter++; //Increase counter
    var clonedBox = $('.input-group').eq(0).clone();
    clonedBox.find('input').attr('id', function(index, attr) {
      return attr + (counter - 1);
    }).val('');
    $("#boxid").append(clonedBox);
    $( "#boxid .countid" ).last().text('UserId'+counter);

    clonedBox = $('.input-group').eq(1).clone();
    clonedBox.find('input').attr('id', function(index, attr) {
      return attr + (counter - 1);
    }).val('');
    $("#boxid").append(clonedBox);
  });

  // WHEN CLICKED ON SUBMIT RETRIEVE ALL DATA\\
  $( "#target" ).submit(function( event ) {
    //alert( "Handler for .submit() called." );

    var dict = {};

    $('#target input[id^="myid"]').each(function(i, e) {
      dict[this.value] = $('#mypwdid' + ((i == 0) ? '' : i)).val();
    })

    console.log('Fields '+ JSON.stringify(dict));




    event.preventDefault();
  });

});
.input-group{
  margin-bottom: 1em;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<button id="btn">Add  row</button>
<form id="target" method="POST">
    <div id="boxid">
        <div id="boxcontainerid" class="form-group">
            <div class="input-group">
                <div class="countid input-group-addon">UserId</div>
                <input type="text" class="form-control" id="myid" placeholder="username" name="1">
                <div class="input-group-addon">?</div>
            </div>

            <div class="input-group">
                <div class="input-group-addon">Password</div>
                <input type="text" class="form-control" name="pwd" id="mypwdid" placeholder="password">
            </div>
            <hr>
        </div>

    </div>
    <button>send</button>
</form>