Reputation: 219
I have huge drop down list with postal numbers. Since it is rather hard to scroll it down with regular drop down list, I have came to idea to implement Select2 jQuery (version 4) drop down (since it feature search function out of the box as well). Now, due to nature of it, and size of list, it takes long time to load, so I though I could use some pagination and limit initial list to 50 items, and on scroll or search to expand it. Eventually I have found out that pagination is reserved for ajax loading (if I am reading the docs correctly) which is something that I would like to avoid.
My current option group looks like this
<option data-name="City Name" data-postal-number="11111">City Name [11111]</option>
In database I am inserting placeholders data-name
and data-postal-number
in two database fields (required by design).
I have managed to create following JS for initialization of Select2 but have no idea how to manage to have placeholders properly set in it to submit it to database (using Codeigniter 3, but doubt thats relevant for the issue)
$.fn.select2.amd.require(
['select2/data/array', 'select2/utils'],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
function contains(str1, str2) {
return new RegExp(str2, "i").test(str1);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
if (!("page" in params)) {
params.page = 1;
}
var pageSize = 50;
var results = this.$element.children().map(function(i, elem) {
if (contains(elem.innerText, params.term)) {
return {
id:[elem.innerText, i].join(""),
text:elem.innerText
};
}
});
callback({
results:results.slice((params.page - 1) * pageSize, params.page * pageSize),
pagination:{
more:results.length >= params.page * pageSize
}
});
};
$("#postal_number_selector").select2({
ajax:{},
allowClear:true,
width:"element",
dataAdapter:CustomData
});
});
Any help or info where to read about it is more than appreciated (would like to avoid real ajax/json loading if possible...)
Thanks in advance
Upvotes: 1
Views: 288
Reputation: 31889
Instead of using HTML data-*
attributes, try to use HTML <option value="...">
.
Then, inside the value, concatenate both City Name
and 11111
, with some separator, for example |||
.
Afterwards you can extract both values server-side (using PHP or ASP for example - it depends on your server-side architecture) by splitting the value sent from option tag (<option value = "City Name|||11111">City Name [11111]</option>
).
This is how I would do it in PHP server-side:
<?php
$select_name = isset($_POST['select_name']) ? $_POST['select_name'] : "";
//Get the value(s) and extract them
$select_value = explode("|||", $select_name);
echo $select_value[0]; //This should contain "City Name"
echo $select_value[1]; //This should contain "11111"
?>
Upvotes: 1