0
votes

I would like a dropdown of text and then when one is selected I would like to load the full value as the tag and have it behave as normal.

I'm capturing the values selected then clearing the list and appending them as text into the .select2-choices div. It appears to work as it should but I've lost the ability to clear the manually appended tags.

Markup:

<div id="select2-container">
    <select multiple class="select2" id="select2">
        <optgroup label="GroupName">
            <option value="John Smith - GroupName (ID:12345678)">John Smith</option>
        </optgroup>
    </select>
</div>

Script:

$('#select2').select2({               
    }).on('change', function (e) {
        values = $(this).val();
        console.log(values);
        $('#select2-container .select2-choices').empty();
        for (var i = 0; i < values.length; i++) {
            console.log(values[i]);
            $('#select2-container .select2-choices').append('<li class="select2-search-choice"><div>' + values[i] + '</div><a href="#" class="select2-search-choice-close" tabindex="-1"></a></li>');
        }
    });

I'm going to look into the formatSelection function but any help is greatly appreciated.

2

2 Answers

1
votes

You've probably solved this by now, but you are correct that you want to use formatSelection.

Be default, the selected object's text property is used, but you want the id property instead. The id property is the <option> element's value.

$('#select2').select2({
    formatSelection: function(object) {
        return object.id;
    }
});

jsfiddle

-1
votes

This is a solution in my project:

In edit.php file:

solution 1 (cate id is single number):

<?php
    $cate_row = $db->fetchRow("SELECT cate_id, cate_name FROM categories WHERE cate_id=".$editdata[cate_id]." AND cate_status='Active'");
    $cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);

    echo "<script type=\"text/javascript\">
        AjaxCombo('#categories', '/ajax/getCategories.php', true)
    </script>";

    echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>

solution 2 (cate id is array: 12,4,5,6 or ,12,4,5,6,):

<?php
    $cate_q = $db->query("SELECT cate_id, cate_name FROM categories WHERE cate_status='Active' ORDER BY cate_name ASC");

    // array: ,12,4,5,6,
    $editcate_array = explode(",", substr($editdata[cate_id], 1, $editdata[cate_id] - 1));
    // or array 12,4,5,6
    // $editcate_array = explode(",", $editdata[cate_id]);

    while($cate_row = $db->fetch_array($cate_q)){
        if(in_array($row['cate_id'], $editcate_array)) {
            $cateArray[] = array("id"=>$cate_row['cate_id'], "text"=>$cate_row['cate_id']." - ".$cate_row['cate_name']);
        }
    }

    echo "<script type=\"text/javascript\">
        AjaxCombo('#categories', '/ajax/getCategories.php', true)
    </script>";

    echo "<input type=\"hidden\" name=\"sl2\" id=\"categories\" value='".json_encode($cateArray)."' data-placeholder=\"Select a category for this product..\" style=\"width: 400px !important;\" />";
?>

In JS global.js:

function AjaxCombo(elm, url, multiple) {
    $(document).ready(function() {
        $(elm).select2({
            multiple: multiple,
            minimumInputLength: 1,
            ajax: {
                url: url,
                dataType: 'json',
                quietMillis: 100,
                data: function (term, page) {
                    return { q: term };
                },
                results: function (data, page) {
                    return {results: data};
                }
            },
            // Add new category if no exist
            createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
        });
        $(elm).select2("data", JSON.parse($(elm).val()));
    });
}

Default if form edit have cate data select2 init "id - Name category".

in file getCategories.php : from select you get $q = $input->gc['q'] and mysql is cate_name LIKE '%" . $q . "%';

while($row = $db->fetch_array($result)){
    $dataArray[] = array("id"=>$row['cate_id'], "text"=>$row['cate_id']." - ".$row['cate_name']);
}

header('Content-Type: application/json');
echo json_encode($answer);

when get value form select2 you can try:

foreach ($_GET['select2'] as $value) {
    echo $value;
}

done!