How can I change hidden input val when add or remove item with using select2 plugin <p>I use select2 plugin and get values when user typing least 3 character. Get data from php as json like this;</p> <pre><code>"1":"val1" , "5":"val2" , "19":"val3".... </code></pre> <p>I want to store id values of selected items at hidden input and when user remove any selected item, the id of removed item also remove from hidden input. For example;</p> <p>When val1 and val2 items are selected like below, value of hidden input (id which 'hdn-id') change like below, also. </p> <p><img src="https://i.stack.imgur.com/ftmw8.jpg" alt="enter image description here"></p> <pre><code>&lt;input type="hidden" id="hdn-id" val="1,5" /&gt; </code></pre> <p>And when val1 is removed, id of this item (1) removed from hidden input like this ;</p> <p><img src="https://i.stack.imgur.com/IfGe8.jpg" alt="enter image description here"></p> <pre><code>&lt;input type="hidden" id="hdn-id" val="5" /&gt; </code></pre> <p>But I can't do this. My codes;</p> <p><strong>SELECT2:</strong></p> <pre><code>function selectAjax(element,url,hiddenElement) { var selectedItemsArray = [] $('#'+element).select2({ multiple: multi, id: function(element) { return element }, ajax: { url: url, dataType: 'json', data: function(term,page) { return { term: term, page_limit: 10 }; }, results: function(data,page) { var titleArr = []; $.each(data, function(k,v){ titleArr.push(k+':'+v); }); return { results: titleArr }; } }, formatResult: formatResult, formatSelection: formatSelection, }); function formatResult(data) { return '&lt;div&gt;'+data.substr(data.indexOf(':')+1)+'&lt;/div&gt;' }; function formatSelection(data) { var id = data.split(':',1), text = data.substr(data.indexOf(':')+1), hiddenElementValue = eval([jQuery('#'+hiddenElement).val()]); selectedItemsArray.push(id); jQuery('#'+hiddenElement).val(selectedItemsArray); return '&lt;div data-id="'+id+'" class="y-select2-selected-items"&gt;'+text+'&lt;/div&gt;'; }; } selectAjax('select2-element','ajx.php','hdn-id'); </code></pre> <p><strong>HTML:</strong></p> <pre><code>&lt;input type="text" id="select2-element" /&gt; &lt;input type="hidden" id="hdn-id" /&gt; </code></pre> <p>I can store ids at hidden input with above code but when remove an item I can't remove id from hidden input. Because plugin assign 'return false' to element's onclick event. I handed the job with above codes, I think.How can I be a better solution?</p>