Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 edit value of selected option

I want to edit option text and value selecting.

<select id="sel">
  <option value="Option one">Option one</option>
  <option value="Option two">Option two</option>
  <option value="Option three">Option three</option>
  <option value="Option four">Option four</option>
</select>

$("#sel").select2({
  width: 400,
  tags: true
});

Let's say I select Option one, and I want to edit it to First Option, both text and value. How can I do it?

After it should looks like

<select id="sel">
      <option value="First option">First option</option>
      <option value="Option two">Option two</option>
      <option value="Option three">Option three</option>
      <option value="Option four">Option four</option>
</select>

Something like this. Before was tEST after tEDT EDIT, and all this I want to do with input of select2

enter image description here

like image 469
Adizbek Ergashev Avatar asked Mar 12 '23 21:03

Adizbek Ergashev


1 Answers

I have solve my problem

var s = $("#sel").select2({
  tags: true,
  closeOnSelect: false,
  width: 400,

});

var $search = s.data('select2').dropdown.$search || $el.data('select2').selection.$search;

s.on("select2:selecting", function(e) {
  $search.val(e.params.args.data.text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" />



<select id="sel">
  <option value="Option one">Option one</option>
  <option value="Option two">Option two</option>
  <option value="Option three">Option three</option>
  <option value="Option four">Option four</option>
</select>
like image 124
Adizbek Ergashev Avatar answered Mar 26 '23 18:03

Adizbek Ergashev