我使用Select2搜索框构建了一个Web应用程序,该搜索框通过AJAX连接到我们的后端。搜索框将查询(例如“APPLES”)传递给后端,然后后端更新页面。如何以编程方式将搜索查询注入搜索框?我需要传入“val”,以便select2通过AJAX调用后端并更新页面。我确信这很明显,但我在文档中找不到它。
例如,我希望用户不要强迫用户在搜索框中输入“APPLES”,而是希望用户点击按钮并在搜索字段中自动填充“APPLES”,然后让页面更新
谢谢!
在Kevin的评论之后,我不是处于这种状态,其中文本嵌入在搜索框中,并且选择器已选择了正确的项目。如何提交(或触发)此请求,我尝试了“keydown”,“pressdown”,“submit”,“click”(清除框)等等。
答案 0 :(得分:33)
Select2用于提供一个if !CGRectIntersectsRect(frame, spriteNode.frame) {
// Outside the bounds of the scene because the frames are no longer intersecting.
}
辅助方法,它可以帮助解决这个问题,但它没有被带到Select2 4.0.0。
有几种方法可以做到这一点,但总的来说它们都遵循相同的步骤模式
select2('search', 'term')
)所以,现在,在Select2 4.0.0中,执行此操作的代码看起来像
input
$('select').select2();
function select2_search ($el, term) {
$el.select2('open');
// Get the search box within the dropdown or the selection
// Dropdown = single, Selection = multiple
var $search = $el.data('select2').dropdown.$search || $el.data('select2').selection.$search;
// This is undocumented and may change in the future
$search.val(term);
$search.trigger('keyup');
}
$('button').on('click', function () {
var $select = $($(this).data('target'));
select2_search($select, 'Arizona');
});
虽然此示例不使用AJAX,但如果为其配置了Select2,它将触发AJAX请求。
答案 1 :(得分:7)
对我来说触发' keyup'仅在用户尚未选择任何选项时才有效。每次都有效的是触发输入'代替。 (仅在Chrome上测试)
基于Kevin Brown的回答:
$('select').select2();
function select2_search ($el, term) {
$el.select2('open');
// Get the search box within the dropdown or the selection
// Dropdown = single, Selection = multiple
var $search = $el.data('select2').dropdown.$search || $el.data('select2').selection.$search;
// This is undocumented and may change in the future
$search.val(term);
$search.trigger('input');
}
$('button').on('click', function () {
var $select = $($(this).data('target'));
select2_search($select, 'Arizona');
});
答案 2 :(得分:4)
您可以将minimumInputLength
设置为0
,然后在data
功能中,您可以检查params.term
length
以及0
if (cluster.isMaster) {
/*
------------------------------------------------------------------------------------
This stores our workers. We need to keep them to be able to reference
them based on source IP address. It's also useful for auto-restart
We also setup a message listener to every worker in order to blast AND FILTER
socket io updates to all nodes.
------------------------------------------------------------------------------------
*/
var workers = [];
var messageRelay = function(msg) {
for(var i = 0; i < workers.length; i++) {
workers[i].send(msg);
}
};
var spawn = function(i) {
workers[i] = cluster.fork();
console.log("Hello from worker %s",workers[i].process.pid);
workers[i].on('message', messageRelay);
/*
----------------------------------------
Restart worker if it gets destroyed
----------------------------------------
*/
workers[i].on('disconnect', function(worker) {
console.log('Worker disconnected');
});
workers[i].on('exit', function(worker, code, signal) {
console.log('respawning worker', i);
spawn(i);
});
};
for (var i = 0; i < cpuCount; i++) {
spawn(i);
}
/*
--------------------------------------------------------------------------------------------
Helper function for getting a worker index based on IP address (supports IPv4 AND IPv6)
This is a hot path so it should be really fast. The way it works
is by converting the IP address to a number by removing the dots (for IPv4) and removing
the :: for IPv6, then compressing it to the number of slots we have.
Compared against "real" hashing (from the sticky-session code) and
"real" IP number conversion, this function is on par in terms of
worker index distribution only much faster.
--------------------------------------------------------------------------------------------
*/
var workerIndex = function (ip, len) {
var _ip = ip.split(/['.'|':']/),
arr = [];
for (el in _ip) {
if (_ip[el] == '') {
arr.push(0);
}
else {
arr.push(parseInt(_ip[el], 16));
}
}
return Number(arr.join('')) % len;
}
/*
------------------------------------------------------------------------------------
Create the outside facing server listening on our port.
------------------------------------------------------------------------------------
*/
var server = net.createServer({ pauseOnConnect: true }, function(connection) {
/*
------------------------------------------------------------------------------------
We received a connection and need to pass it to the appropriate
worker. Get the worker for this connection's source IP and pass
it the connection.
------------------------------------------------------------------------------------
*/
if(connection.remoteAddress === undefined) {
console.log("BLEH: %o ", connection.remoteAddress);
return;
}
else {
var worker = workers[workerIndex(connection.remoteAddress, cpuCount)];
worker.send('sticky-session:connection', connection);
}
}).listen(port, function() {
console.log("Spun up worker %s", process.pid);
console.log('Server listening on *:' + port);
});
}
else {
var sio = require('socket.io');
var redis = require('socket.io-redis');
var ioEvents = require(__base + 'lib/ioEvents');
var app = new express();
/*
------------------------------------------------------------------------------------
Note we don't use a port here because the master listens on it for us.
------------------------------------------------------------------------------------
*/
var server = app.listen(0, 'localhost'),
io = sio(server);
/*
----------------------------------------------------------------------------------------------
Using Redis as the store instead of memory. This allows us to blast socket updates
to all processes (unfiltered). For example, we can do io.sockets.emit("message")
and it will be distributed to all node processes.
We cannot filter these messages to specific socket connections or specific configurations
(e.g. updateSquares(socket)), in order to do that we must blast an update to all workers
and let each process filter the request individually.
----------------------------------------------------------------------------------------------
*/
io.adapter(redis({host:'localhost', port: portRedis}));
/*
------------------------------------------------------------------------------------
Setup the socket listeners
------------------------------------------------------------------------------------
*/
ioEvents.incoming(io);
/*
------------------------------------------------------------------------------------
Listen to master for worker process updates
------------------------------------------------------------------------------------
*/
process.on('message', function(message, connection) {
/*
------------------------------------------------------------------------------------
Listen for special updates to all nodes
------------------------------------------------------------------------------------
*/
if(message.squareUpdate) {
console.log("worker %s received message %o", process.pid, message.squareUpdate);
ioEvents.squaresForceUpdate(message.squareUpdate);
}
/*
------------------------------------------------------------------------------------
If it's not a special message, then check to make sure it's just a sticky-session
Otherwise, just bail, no need to do anything else
------------------------------------------------------------------------------------
*/
if (message !== 'sticky-session:connection') {
return;
}
/*
------------------------------------------------------------------------------------
| Emulate a connection event on the server by emitting the
| event with the connection the master sent us.
------------------------------------------------------------------------------------
*/
server.emit('connection', connection);
connection.resume();
});
},将过滤器值设置为预定义的搜索值。
这很傻,但它有效;)
答案 3 :(得分:2)
作为此答案的补充,我们尝试以编程方式向配置用于标记的select2添加新的“标记”。我们不必在$ search框上触发keyup事件,而是必须执行以下操作。
$search.val(tag);
$search.closest('.select2-search--inline')
.trigger($.Event('input', { which: 13 }));
$search.closest('.select2-selection--multiple')
.trigger($.Event('keydown', { which: 13 }));
这首先触发一个事件,导致select2中的'search'模块添加一个包含标记文本的'highlight'结果,然后第二个事件导致select2在内部触发'select'事件,这会向select2选项,也可能触发其他内容,具体取决于您的配置方式。
答案 4 :(得分:2)
对于那些使用 Ajax 调用来填充 select2 并希望搜索和设置选定值的人。
您还有其他方法可以使用,但是使用 Select2 4.0.0
,这个答案对我来说非常有用JS
$('.select2').select2();
function select2_search_and_set(controlId, term) {
var control = $("#" + controlId);
var $search = control.data('select2').dropdown.$search || control.data('select2').selection.$search;
$search.val(term);
$search.trigger('keyup');
setTimeout(function () {
$search.trigger($.Event('keydown', { which: 13 }));
}, 500);
}
select2_search_and_set("target", 'term');
HTML
<select class="form-control select2" id="target" name="target"></select>
答案 5 :(得分:1)
这个页面上的答案让我几乎到了那里。而且因为其他人似乎有同样的问题,我分享我是如何解决它的。
Kevin Browns的一些评论回答了在输入文本后如何模拟ENTER并突出显示。
我设法只在暂停时才这样做:
setTimeout(function() { $('.select2-results__option').trigger("mouseup"); }, 500);
所以,完整的解决方案就是:
$('select').select2();
function select2_search ($el, term) {
$el.select2('open');
// Get the search box within the dropdown or the selection
// Dropdown = single, Selection = multiple
var $search = $el.data('select2').dropdown.$search || $el.data('select2').selection.$search;
// This is undocumented and may change in the future
$search.val(term);
$search.trigger('input');
setTimeout(function() { $('.select2-results__option').trigger("mouseup"); }, 500);
}
$('button').on('click', function () {
var $select = $($(this).data('target'));
select2_search($select, 'Arizona');
});
答案 6 :(得分:1)
我一直在发疯,直到我来到这个线程。我想要一个 select2 对话框,用户可以在其中输入一个名称,该名称可能不是选项之一,但我仍然可以设置它并且是可见的。
借助这里的答案形式组合,我设法解决了我的问题。
要做到这一点:
我首先需要将 select2 上的标签选项设置为 true
没有必要打开 select2
我需要将触发器从“keyup”更改为“input”
我需要在最后添加以下行来模拟输入键 $('.select2-results__option').trigger("mouseup");
Here is the jsfiddle sample for you to try for yourself
https://jsfiddle.net/jainpankaj/o8g37wfu/8/#&togetherjs=I0e96aNexC