Space Peasant Space Peasant - 5 months ago 10
jQuery Question

Get last tag data on change

I have this code:

var i = 0;
$('#jobs').change(function() {
var id = $(this).select2('data')[i].id;
var txt = $(this).select2('data')[i].text;
$('#jobSection').append('<fieldset><legend>' + txt + '</legend><input type="text" class="form-control" name="size_' + id + '" placeholder="Size"><br/><select class="form-control" name="type_' + id + '"><option>Type</option><option value="1">Type 1</option><option value="2">Type 2</option></select></fieldset>');
i++
});


With that I am appending extra input fields for each tag.

But it works only if I select tags by order otherwise it takes previous tag data.

I understand that problem is in
i
because this is not actual loop but change event.

So I want to know how to get just last tag data on change?

Full example is here

Answer

 var selectOption = [{
   "id": 1,
   "text": "one"
 }, {
   "id": 2,
   "text": "two"
 }, {
   "id": 3,
   "text": "three"
 }, {
   "id": 4,
   "text": "four"
 }, {
   "id": 5,
   "text": "five"
 }];
 $('#jobs').select2({
   tags: true,
   multiple: true,
   placeholder: 'Choose job...',
   data: selectOption
 });


 $('#jobs').change(function() {
   var thisVal = $(this)[0].value.split(',');
   var i = thisVal[thisVal.length - 1] - 1;
   var id = selectOption[i].id;
   var txt = selectOption[i].text;
   $('#jobSection').append('<fieldset><legend>' + txt + '</legend><input type="text" class="form-control" name="size_' + id + '" placeholder="Size"><br/><select class="form-control" name="type_' + id + '"><option>Type</option><option value="1">Type 1</option><option value="2">Type 2</option></select></fieldset>');
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>

<div id="jobSection">
  <input type="text" id="jobs">
</div>

Refer : JSFiddle

Comments