目前,我有一个web应用程序本机不支持多选,这给我的设计带来了一些问题。因此,我正在尝试创建一个多选,并创建一个jquery脚本来填充基于文本输入的多选。下面是我目前正在做的事情的链接,它有效,但一次只能选择一个。我需要它,这样,如果用户在test1、test2、test3中键入,那么所有3个选项都会被选中。如有任何帮助,我们将不胜感激。
http://jsfiddle.net/C83DB/11/
selectOptions = {
test1: ["test1"],
test2: ["test2"],
test3: ["test3"]
}
$('#input').change(function() {
if(selectOptions[$(this).val()]) { // does the option have an entry for the value of the textarea?
$.each(selectOptions[$(this).val()], function() { // for each array item do
$('#sel').append('<option>' + this + '</option>'); // append an option tag for the array item
});
}
});
I trimmed input field and splited it
selectOptions = {
test1: ["test1"],
test2: ["test2"],
test3: ["test3"]
}
$('#input').change(function()
{
//getting all values seperated by","
var values = $(this).val().split(",");
values = $.map(values, function(elem) {return elem.trim()});
$.each(values, function(i, value)
{
if(selectOptions[value])
{
$.each(selectOptions[value], function()
{
//append the option tag
$('#sel').append('<option>' + this + '</option>');
});
}
})
});
一个更好的解决方案。
<input type='text' id='txt'>
<select multiple id='sel'>
<option value='test1'> test1 </option>
<option value='test2'> test2 </option>
<option value='test3'> test3 </option>
<option value='test4'> test4 </option>
<option value='test5'> test5 </option>
<option value='test6'> test6 </option>
</select>
<script>
$("#txt").change(function(){
$("#sel").val($(this).val().split(","))
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type='text' id='txt'>
<select multiple id='sel'>
<option value='test1'> test1 </option>
<option value='test2'> test2 </option>
<option value='test3'> test3 </option>
<option value='test4'> test4 </option>
<option value='test5'> test5 </option>
<option value='test6'> test6 </option>
</select>
<script>
$("#txt").change(function(){
$("#sel").val($(this).val().split(","))
});
</script>
我对输入字段中的文本进行了拆分和修剪,以便将类似"test1、test2、test3"的输入转换为值"test1"、"test2"answers"test3"。对于每一个,我们都在selectOption对象中进行检查
http://jsfiddle.net/dzda0xvL/3/
selectOptions = {
test1: ["test1"],
test2: ["test2"],
test3: ["test3"]
}
$('#input').change(function() {
// get all values splited by ","
var values = $(this).val().split(",");
// remove blank space before and after each values
values = $.map(values, function(elem) {return elem.trim()});
// for each value
$.each(values, function(i, value) {
// does the option have an entry for the value?
if(selectOptions[value]) {
// for each array item do
$.each(selectOptions[value], function() {
// append an option tag for the array item
$('#sel').append('<option>' + this + '</option>');
});
}
})
});