Alejandro Espinel Alejandro Espinel - 2 months ago 13
jQuery Question

Getting single value of selected option Select2

I am working using select2 on this select menu:

<select id="documents" name="documents[]" class="form-control" multiple="">
<option value="1">My first document</option>
<option value="2">This is my second document</option>
<option value="3">This is my third document</option>
</select>


And this is my js:

$('#documents').on("select2:selecting", function(e) {
var documentSelected = $("#documents").select2("val");
var documentListCreate =
'<tr data-value='+documentSelected+'>' +
'<td width="30px">' +
'<button type="button" class="btn btn-default btn-xs delete-doc"><i class="fa fa-times"></i></button>' +
'</td>' +
'<td width="50px">' +
'<a href="../samples/sample.pdf" target="_blank"><img style="margin-bottom:10px;" class="document-icon" src="..img/pdf_icon.png"></a>' +
'</td>' +
'<td>' +
'<a class="nounderlink" href="../samples/sample.pdf" target="_blank">Document_455.pdf<br><span class="text-muted">Description of document</span></a>'+
'</td>' +
'</tr>';
$("#document-list").append(documentListCreate);
});


I am trying to append a list of documents formatted my way when a selection is made in select2. I am trying to get the value of the option selected but when I do it as shown above, I get an array of all the values in the select2. What is the best way for me to get just that one single value on click which in turn will be appended to the list of documents with the "tr data-value" being the value of that selection only.

Any help is appreciated, thank you!!!

Answer

Select2 doesn't have a specific event that gives you the element that was added, but you can use the select2:selecting event and the data from the specific element that you clicked on:

$(document).ready(function() {
  $("#documents")
    .select2()
    .on("select2:selecting", function(e) { 
      item = $(e.params.args.originalEvent.toElement).data('data')
      console.log("The item that was clicked is '"+item.text+"' and the value of the item is '"+item.id+"'");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="documents" name="documents[]" class="form-control" multiple="">
    <option value="1">My first document</option>
    <option value="2">This is my second document</option>
    <option value="3">This is my third document</option>
</select>