我试图找到一种方法,以便当用户在数据列表中输入文本时,他们可以按课程编号(EG“CS 101”)或课程名称(EG“计算机科学简介”)查看相同的条目。
目前,我所拥有的只能通过值字段进行搜索:
<datalist id="tagList">
<option value=""></option>
<option value="CSCI 4950">Senior Software Project</option>
<option value="CSCI 5117">Developing the Interactive Web</option>
<option value="CSCI 5421">Advanced Algorithms</option>
<option value="CSCI 5980">Design Methods for Comp. Sci.</option>
</datalist>
我尝试了什么
https://stackoverflow.com/a/22827978/2831961 - 出于某种原因,这不起作用。
我也尝试了类似的策略,但是使用了data-value属性。那也行不通。除非我负责幕后的Javascript工作,我不知道。
答案 0 :(得分:0)
http://jsfiddle.net/rh48cgrj/3/
这是一个小提琴。我将选项值/文本放入javascript对象中的key:value对。注意:键是索引号,值是选项值属性和文本。这样可以更容易地搜索它们的文本。
var i = 0;
var selectItems = {}
$('#tagList option').each(function() {
var listvalue = $(this).val();
var listtext = $(this).text();
selectItems[i] = listvalue + " " + listtext + ",";
i++;
});
然后我将它们分成包含值和文本的行。
count = i;
for(i=0; i < count;i++) {
var blockoftext = blockoftext + " " + selectItems[i].toLowerCase() + ",";
}
然后我设置了一个搜索功能,搜索这些行以查看是否有任何返回的匹配,如果是,则结果输出到搜索框下方的div。
var texttosplit = blockoftext.split(",");
var searchresults;
for(i=0; i < texttosplit.length; i++) {
(texttosplit[i].indexOf(searchvalue.toLowerCase()) != -1) ?
(searchresults = texttosplit[i] + "<br>") : false;
$("#searched").html(searchresults);
}
小提琴中有上述所有内容的例子。
编辑:以下是循环的注释代码,用于检查搜索文本是否在每个操作请求的数据列表中。
for (i = 0; i < texttosplit.length; i++) {
//The above loops through our array of class values and titles
(texttosplit[i].indexOf(searchvalue.toLowerCase()) != -1) ?
// The above determines if our search text is in class title using a ternary operator
// our array of class values and titles is lowercase so we make
//sure our search text is lowercase as well
// if we find a match between the search text and the class title/values perform the following:
(searchresults = texttosplit[i].replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
})
// The above replaces the first char of every word with an uppercase char
.replace("Csci", "CSCI") + "<br>",
// The above finds Csci and changes it to CSCI since all THOSE letters should be uppercase
prevtext = $("#searched").html(),
//get current text of element with id "searched" and place it in prevtext
$("#searched").html(prevtext + searchresults))
//append "searched" by adding it's current text with the new searchresults
:
//if search text is not in the class title return false
false;
}