Illep Illep - 1 year ago 104
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
will appear as shown in the jsfiddle link below.

Now, when the user submits the form by clicking on the
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 Source

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);
    $( "#boxid .countid" ).last().text('UserId'+counter);

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

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


  margin-bottom: 1em;
<script src=""></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 class="input-group">
                <div class="input-group-addon">Password</div>
                <input type="text" class="form-control" name="pwd" id="mypwdid" placeholder="password">


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download