OiO.lk Blog jQuery How to add actual option value into list item?
jQuery

How to add actual option value into list item?


Using the select2 javascript for select boxes, it basically hides the actual real select box and gives you a span with a ul li list inside.

However, the li options don’t have the actual real value from the original.

Is there a way to make it so the li items for select2 have the real value?

For example this is the original:

<option value="2" selected="" data-select2-id="6">Test Item</option>

Select2 will turn that into:

<li class="select2-selection__choice" title="Test Item" data-select2-id="7"><span class="select2-selection__choice__remove" role="presentation">×</span>Test Item</li>

What I would like, is the real value "2" added into it so I can easily pull it using any outside JS. Something like data-real-value="2" or whatever will do fine.

I’m using it for multi-select, using AJAX to actually pull the results like so:

var $selectclass = $("#select2ajax").select2({
    selectOnClose: true,
    width: '100%',
    ajax: {
      url: "ajaxcall.php",
      dataType: 'json',
      delay: 250,
      data: function (params) {
        return {
          q: params.term // search term
        };
      },
      processResults: function (data) {
        return {
          results: $.map(data, function(obj) {
            return { id: obj.id, text: obj.text };
          })
        };
      },
      cache: true,
    },
    minimumInputLength: 2,
    containerCssClass: 'class',
    dropdownCssClass: 'class',
    });

If you’re wondering why, I simply want to able to detect when someone has mouse clicked on an existing tag that’s in the list, to then do something. Select2 doesn’t seem to have an option to do that directly, only when stuff is "selected" (added) into the box. Unless I am mistaken.



You need to sign in to view this answers

Exit mobile version