简体   繁体   English

jquery select2 - 选择带有输入文本字符串的所有选项

[英]jquery select2 - Select all options with inputted text string

What i'm trying to achieve here is I have a text input, and when I type in a string for example "HELP" - I want all the option texts that are "HELP" to be auto-selected in the list. 我在这里想要实现的是我有一个文本输入,当我输入一个字符串例如“HELP”时 - 我希望在列表中自动选择所有“帮助”的选项文本。

Sorry I should mention im using the select2 plugin for jquery 对不起我应该提到我使用jquery的select2插件

example--> 示例 - >

html: HTML:

<select id="select2" name="select2" multiple class="select2" style="width: 300px;">
<option value="1">ABC</option>
<option value="2">BPS</option>
<option value="3">BPS</option>
<option value="4">HELP</option>
<option value="5">HELP</option>
<option value="6">EX</option>
<option value="7">HELP</option>    
</select>

<br /><br />

<input type="button" name="Button" id="selectspecify" value="Select String" />&nbsp;
<input size="50" name="selectstring" id="selectstring" value="" placeholder="Type in an option name">

jquery: jQuery的:

$('#selectspecify').click(function() {
    var selectstring = $('#selectstring').val();

    $('#select2\\[\\] option:contains(' + selectstring + '))').select2('destroy').find('option').prop('selected', 'selected').end().select2() 

});

$(".select2").select2();

Can someone help me with this please? 请有人帮我这个吗?

I've made a jsfiddle to show what i'm trying todo: http://jsfiddle.net/3ZhWu/2/ But it obviously doesn't work yet. 我已经做了一个jsfiddle来展示我正在尝试的东西: http//jsfiddle.net/3ZhWu/2/但它显然还没有用。

Try this: 尝试这个:

$('#selectspecify').click(function() {
    var selectstring = $('#selectstring').val();
    var stringVal = [];
    $('#select2').find('option').each(function(){
        if($(this).is(':contains(' + selectstring + ')')){
                  stringVal.push($(this).val());
        }
        $('#select2').val(stringVal).trigger("change");
    });
});

$(".select2").select2();

Ref: http://ivaynberg.github.io/select2/ 参考: http//ivaynberg.github.io/select2/

DEMO DEMO

$('#selectspecify').click(function() {
    $('#select2').select2("val", $('#select2 option:contains(' + selectstring + ')')
    .map(function(){
        return $(this).val();
    }).get());
});

Try: http://jsfiddle.net/L4ob780b/2/ 试试: http//jsfiddle.net/L4ob780b/2/

$( "option:contains('Help')" );

参考

Try this... 尝试这个...

$('#selectspecify').click(function() {
    var selectstring = $('#selectstring').val().toLowerCase();

$('#select2 option').each(function() {

    var inval = $(this).html().toLowerCase();
    console.log(inval);
    if(inval.indexOf(selectstring) != -1) {

        $(this).prop('selected',true);
    }
});
});

This one actually checks for substring. 这个实际上检查子字符串。 so even if you give 'h'. 所以即使你给'h'。 It will select the options. 它将选择选项。 If you want exactly same string use an equality check. 如果要完全相同的字符串,请使用相等性检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM