Studento919 Studento919 - 3 months ago 7
jQuery Question

Loop round array, append input text boxes then set values of those text boxes

I am trying to loop round and append a number of containers based on the values stored in an array, then set those values accordingly but I am currently duplicating those values and cant get the values to be different for each time it goes around the loop.



var arr_tele = ['02991812376', '02982919291'];

//Prevent Duplicates.
$(".teledivcontain").remove();

//Append Container for numbers
$("#telediv").append('<div class="form-group col-md-3" id="teledivcontain"> </div>');

//Loop and append fields for each number
for (i in arr_tele) {
$("#teledivcontain").append('<input type="text" class="form-control telenumber" placeholder="No number currently" disabled><div class="form-group col-md-3"><button type="submit" class="btn btn-primary form-control detach">Detach</button></div>').find('input:text').val(arr_tele[i]);
}

.fieldpos {
margin-left: 45px;
width: 40%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="panel-body row fieldpos">
<fieldset class="form-group">
<label for="telenum">Your Telephone Numbers</label>
<div class="row">
<div id="telediv">
</div>
</div>
</fieldset>
</div>





I am missing something minor but cant see what anyone any ideas?

Answer

You have to find the last input appended then assign the value, so just adding the :last selector will do the work :

.find('input:text:last').val(arr_tele[i])

Or you could just assign the value directly using <input value="'+arr_tele[i]+'" ....

Hope this helps.

var arr_tele = ['02991812376', '02982919291'];

//Prevent Duplicates.
$(".teledivcontain").remove();

//Append Container for numbers
$("#telediv").append('<div class="form-group col-md-3" id="teledivcontain"> </div>');

//Loop and append fields for each number
for (i in arr_tele) {
  $("#teledivcontain").append('<input type="text" class="form-control telenumber" placeholder="No number currently" disabled><div class="form-group col-md-3"><button type="submit" class="btn btn-primary form-control detach">Detach</button></div>').find('input:text:last').val(arr_tele[i]);
}
.fieldpos {
  margin-left: 45px;
  width: 40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="panel-body row fieldpos">
  <fieldset class="form-group">
    <label for="telenum">Your Telephone Numbers</label>
    <div class="row">
      <div id="telediv">
      </div>
    </div>
  </fieldset>
</div>

Comments