Reputation: 23
Hi I new with java script.
I try to save in array all selected tags, its work ok, but when I press 'x' on tag I want then delete from this array, how can I do this?
$( "#select2-2" ).change(function() {
$( "#select2-2 option:selected" ).each(function() {
strArr[i] = $( this ).text();
i++;
});
}).trigger("change");
My html code:
<select id="select2-2" class="form-control" multiple>
<option>tag1</option>
<option>tag2</option>
<option>tag3</option>
<option>tag4</option>
<option>tag5</option>
</select>
More explain about Select-2:
select-2 create tags when you select option from select list, like this:
[tag3 x][tag2 x][tag4 x]
When I select option from select list, I get it like visual tag.. so I save the tags in array. But when I press 'x' I want remove this tag from my array.
Any idea how can I do this?
Upvotes: 1
Views: 1523
Reputation: 8513
Add a remove button, then link it to this bit of code: $('#select2-2').find(':selected').remove(); Which will remove all selected options within select2-2
var strArr = [];
$("#select2-2").change(function () {
var i = 0;
$("#select2-2 option:selected").each(function () {
strArr[i] = $(this).text();
i++;
});
}).trigger("change");
$('#remove').click(function(){
$('#select2-2').find(':selected').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select2-2" class="form-control" multiple>
<option>tag 1</option>
<option>tag 2</option>
<option>tag 3</option>
<option>tag 4</option>
<option>tag 5</option>
</select><br>
<button id="remove" type="button">Remove</button>
Upvotes: 1