Reputation: 1322
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.
Sorry I should mention im using the select2 plugin for jquery
example-->
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" />
<input size="50" name="selectstring" id="selectstring" value="" placeholder="Type in an option name">
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.
Upvotes: 0
Views: 5887
Reputation: 2043
$('#selectspecify').click(function() {
$('#select2').select2("val", $('#select2 option:contains(' + selectstring + ')')
.map(function(){
return $(this).val();
}).get());
});
Try: http://jsfiddle.net/L4ob780b/2/
Upvotes: 1
Reputation: 20313
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/
Upvotes: 1
Reputation: 1102
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'. It will select the options. If you want exactly same string use an equality check.
Upvotes: 0