如何使用 MaterializeCss 创建自动完成表单?
Posted
技术标签:
【中文标题】如何使用 MaterializeCss 创建自动完成表单?【英文标题】:How to create autocomplete form with MaterializeCss? 【发布时间】:2016-03-17 07:42:40 【问题描述】:我正在寻找 MaterializeCss 的自动完成表单,有任何插件吗?我曾尝试使用 select2,但 css 看起来不太好
【问题讨论】:
似乎我们需要编写自定义样式:/ 自动完成表单是什么意思? 【参考方案1】:Materialize 是一个很棒的库,我能够让它工作。
$('document').ready(function()
var input_selector = 'input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], textarea';
/**************************
* Auto complete plugin *
*************************/
$(input_selector).each(function()
var $input = $(this);
if ($input.hasClass('autocomplete'))
var $array = $input.data('array'),
$inputDiv = $input.closest('.input-field'); // Div to append on
// Check if "data-array" isn't empty
if ($array !== '')
// Create html element
var $html = '<ul class="autocomplete-content hide">';
for (var i = 0; i < $array.length; i++)
// If path and class aren't empty add image to auto complete else create normal element
if ($array[i]['path'] !== '' && $array[i]['path'] !== undefined && $array[i]['path'] !== null && $array[i]['class'] !== undefined && $array[i]['class'] !== '')
$html += '<li class="autocomplete-option"><img src="' + $array[i]['path'] + '" class="' + $array[i]['class'] + '"><span>' + $array[i]['value'] + '</span></li>';
else
$html += '<li class="autocomplete-option"><span>' + $array[i]['value'] + '</span></li>';
$html += '</ul>';
$inputDiv.append($html); // Set ul in body
// End create html element
function highlight(string)
$('.autocomplete-content li').each(function()
var matchStart = $(this).text().toLowerCase().indexOf("" + string.toLowerCase() + ""),
matchEnd = matchStart + string.length - 1,
beforeMatch = $(this).text().slice(0, matchStart),
matchText = $(this).text().slice(matchStart, matchEnd + 1),
afterMatch = $(this).text().slice(matchEnd + 1);
$(this).html("<span>" + beforeMatch + "<span class='highlight'>" + matchText + "</span>" + afterMatch + "</span>");
);
// Perform search
$(document).on('keyup', $input, function()
var $val = $input.val().trim(),
$select = $('.autocomplete-content');
// Check if the input isn't empty
$select.css('width',$input.width());
if ($val != '')
$select.children('li').addClass('hide');
$select.children('li').filter(function()
$select.removeClass('hide'); // Show results
// If text needs to highlighted
if ($input.hasClass('highlight-matching'))
highlight($val);
var check = true;
for (var i in $val)
if ($val[i].toLowerCase() !== $(this).text().toLowerCase()[i])
check = false;
;
return check ? $(this).text().toLowerCase().indexOf($val.toLowerCase()) !== -1 : false;
).removeClass('hide');
else
$select.children('li').addClass('hide');
);
// Set input value
$('.autocomplete-option').click(function()
$input.val($(this).text().trim());
$('.autocomplete-option').addClass('hide');
);
else
return false;
);
);
.autocomplete-content
position: absolute;
background: #383838;
margin-top: -.9rem;
.autocomplete-content li
clear: both;
color: rgba(0, 0, 0, 0.87);
cursor: pointer;
line-height: 0;
width: 100%;
text-align: left;
text-transform: none;
padding: 10px;
.autocomplete-content li > span
color: #ffa726;
font-size: .9rem;
padding: 1.2rem;
display: block;
.autocomplete-content li > span .highlight
color: #000000;
.autocomplete-content li img
height: 52px;
width: 52px;
padding: 5px;
margin: 0 15px;
.autocomplete-content li:hover
background: #eee;
cursor: pointer;
.autocomplete-content > li:hover
background: #292929;
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="row">
<div class="input-field col s12">
<label class="active">State</label>
<input type="text" id="autocompleteState" class="autocomplete inputFields">
</div>
</div>
<script>
var stateData = [
value: "Alabama"
,
value: "Alaska"
,
value: "Arizona"
,
value: "Arkansas"
,
value: "California"
,
value: "Colorado"
,
value: "Connecticut"
,
value: "District of Columbia"
,
value: "Delaware"
,
value: "Florida"
,
value: "Georgia"
,
value: "Hawaii"
,
value: "Idaho"
,
value: "Illinois"
,
value: "Indiana"
,
value: "Iowa"
,
value: "Kansas"
,
value: "Kentucky"
,
value: "Louisiana"
,
value: "Maine"
, ];
$('#autocompleteState').data('array', stateData);
</script>
希望这可以帮助像我一样的新手。:)
【讨论】:
【参考方案2】:2016 年 1 月 9 日更新: 自动完成功能已经正式可用: http://materializecss.com/forms.html#autocomplete
我一直在寻找完全相同的东西,我认为我们很幸运。他们最近添加了自动完成功能(尚未在文档中)。但是你可以在这里看到信息https://github.com/SuperDJ/materialize/commit/3648f74542e41c3b3be4596870b7485f6ebdf176#diff-e4535828acef79852aa104417c16fe3dR157
和代码:
https://github.com/SuperDJ/materialize/blob/master/bin/materialize.css
https://github.com/SuperDJ/materialize/blob/master/bin/materialize.js
【讨论】:
遗憾的是它还没有被合并到官方仓库中。 感谢@Saitama 我已经更新了,不可以在当前版本的materializecss materializecss.com/forms.html#autocomplete上找到自动完成功能@【参考方案3】:(function (root, factory)
if(typeof module === 'object' && module.exports)
module.exports = factory(require('jquery'));
else if(typeof define === 'function' && define.amd)
define(['jquery'], factory);
else
factory(root.jQuery);
(this, function ($)
var template = function (text)
var matcher = new RegExp('<%=([\\s\\S]+?)%>|<%([\\s\\S]+?)%>|$', 'g');
var escapes =
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
;
var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match)
return '\\' + escapes[match];
;
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, interpolate, evaluate, offset)
source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
index = offset + match.length;
if (match == "<% item.value %>")
interpolate = " item.value ";
if (interpolate)
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
else if (evaluate)
source += "';\n" + evaluate + "\n__p+='";
return match;
);
source += "';\n";
source = 'with(obj||)\n' + source + '\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function()__p+=__j.call(arguments,'');;\n" +
source + 'return __p;\n';
var render;
try
render = new Function('obj', source);
catch (e)
e.source = source;
throw e;
var _template = function(data)
return render.call(this, data);
;
_template.source = 'function(obj)\n' + source + '';
return _template;
;
var Autocomplete = function (el, options)
this.options = $.extend(true, , Autocomplete.defaults, options);
this.$el = $(el);
this.$wrapper = this.$el.parent();
this.compiled = ;
this.$dropdown = null;
this.$appender = null;
this.$hidden = null;
this.resultCache = ;
this.value = '';
this.initialize();
;
Autocomplete.defaults =
cacheable: true,
limit: 10,
multiple:
enable: false,
maxSize: 4,
onExist: function (item)
Materialize.toast('Tag: ' + item.text + '(' + item.id + ') is already added!', 2000);
,
onExceed: function (maxSize, item)
Materialize.toast('Can\'t add over ' + maxSize + ' tags!', 2000);
,
onAppend: function (item)
var self = this;
self.$el.removeClass('active');
self.$el.click();
,
onRemove: function (item)
var self = this;
self.$el.removeClass('active');
self.$el.click();
,
hidden:
enable: true,
el: '',
inputName: '',
required: false
,
appender:
el: '',
tagName: 'ul',
className: 'ac-appender',
tagTemplate: '<div class="chip" data-id="<%= item.id %>" data-value="<% item.value %> data-text="<% item.text %>" "><%= item.text %>(<%= item.id %>)<i class="material-icons close">close</i></div>'
,
dropdown:
el: '',
tagName: 'ul',
className: 'ac-dropdown',
itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-value="<% item.value %>" data-text="<%= item.text %>" ><a href="javascript:void(0)"><%= item.text %></a></li>',
noItem: ''
,
handlers:
'setValue': '.ac-dropdown .ac-item',
'.ac-appender .ac-tag .close': 'remove'
,
getData: function (value, callback)
callback(value, []);
,
onSelect: function (item) ,
onRemove: function (item) alert('delete'); ,
ignoreCase: true,
throttling: true,
showListOnFocus: false,
minLength:0
;
Autocomplete.prototype =
constructor: Autocomplete,
initialize: function ()
var self = this;
var timer;
var fetching = false;
function getItemsHtml (list)
var itemsHtml = '';
if (!list.length)
return self.options.dropdown.noItem;
list.forEach(function (item, idx)
if (idx >= self.options.limit)
return false;
itemsHtml += self.compiled.item( 'item': item);
);
return itemsHtml;
function handleList (value, list)
var itemsHtml = getItemsHtml(list);
var currentValue = self.$el.val();
if (self.options.ignoreCase)
currentValue = currentValue.toUpperCase();
if (self.options.cacheable && !self.resultCache.hasOwnProperty(value))
self.resultCache[value] = list;
if (value !== currentValue)
return false;
if(itemsHtml)
self.$dropdown.html(itemsHtml);
self.$dropdown.show();
else
self.$dropdown.hide();
self.value = self.options.multiple.enable ? [] : '';
self.compiled.tag = template(self.options.appender.tagTemplate);
self.compiled.item = template(self.options.dropdown.itemTemplate);
self.render();
if (self.options.showListOnFocus)
self.$el.on('focus', function (e)
if (self.options.throttling)
clearTimeout(timer);
timer = setTimeout(function ()
self.options.getData('', handleList);
, 200);
return true;
// self.$dropdown.show();
);
self.$el.on('input', function (e)
var $t = $(this);
var value = $t.val();
if (!value)
self.$dropdown.hide();
return false;
if (self.options.ignoreCase)
value = value.toUpperCase();
if (self.resultCache.hasOwnProperty(value) && self.resultCache[value])
handleList(value, self.resultCache[value]);
return true;
if (self.options.showListOnFocus || self.options.minLength <= value.length)
if (self.options.throttling)
clearTimeout(timer);
timer = setTimeout(function ()
self.options.getData(value, handleList);
, 200);
return true;
self.options.getData(value, handleList);
);
self.$el.on('keydown', function (e)
var $t = $(this);
var keyCode = e.keyCode;
var $items, $hover;
// BACKSPACE KEY
if (keyCode == '8' && !$t.val())
if (!self.options.multiple.enable)
return true;
if (!self.value.length)
return true;
var lastItem = self.value[self.value.length - 1];
self.remove(lastItem);
return false;
// UP DOWN ARROW KEY
if (keyCode == '38' || keyCode == '40')
$items = self.$dropdown.find('[data-id]');
if (!$items.size())
return false;
$hover = $items.filter('.ac-hover');
if (!$hover.size())
$items.removeClass('ac-hover');
$items.eq(keyCode == '40' ? 0 : -1).addClass('ac-hover');
else
var index = $hover.index();
$items.removeClass('ac-hover');
$items.eq(keyCode == '40' ? (index + 1) % $items.size() : index - 1).addClass('ac-hover');
return false;
// ENTER KEY CODE
if (keyCode == '13')
$items = self.$dropdown.find('[data-id]');
if (!$items.size())
return false;
$hover = $items.filter('.ac-hover');
if (!$hover.size())
return false;
self.setValue(
id: $hover.data('id'),
text: $hover.data('text'),
value: $hover.data('value')
);
return false;
);
self.$dropdown.on('click', '[data-id]', function (e)
var $t = $(this);
var item =
id: $t.data('id'),
text: $t.data('text'),
value : $t.data('value')
;
self.setValue(item);
);
self.$appender.on('click', '[data-id] .close', function (e)
var $t = $(this);
var $li = $t.closest('[data-id');
var item =
id: $li.data('id'),
text: $li.data('text'),
value:$t.data('value')
;
self.remove(item);
);
,
render: function ()
var self = this;
if (self.options.dropdown.el)
self.$dropdown = $(self.options.dropdown.el);
else
self.$dropdown = $(document.createElement(self.options.dropdown.tagName));
self.$dropdown.insertAfter(self.$el);
self.$dropdown.addClass(self.options.dropdown.className);
if (self.options.appender.el)
self.$appender = $(self.options.appender.el);
else
self.$appender = $(document.createElement(self.options.appender.tagName));
self.$appender.insertBefore(self.$el);
if (self.options.hidden.enable)
if (self.options.hidden.el)
self.$hidden = $(self.options.hidden.el);
else
self.$hidden = $('<input type="hidden" class="validate" />');
self.$wrapper.append(self.$hidden);
if (self.options.hidden.inputName)
self.$el.attr('name', self.options.hidden.inputName);
if (self.options.hidden.required)
self.$hidden.attr('required', 'required');
self.$appender.addClass(self.options.appender.className);
,
setValue: function (item)
var self = this;
if (self.options.multiple.enable)
self.append(item);
else
self.select(item);
,
append: function (item)
var self = this;
var $tag = self.compiled.tag( 'item': item );
if (self.value.some(function (selectedItem)
return selectedItem.id === item.id;
))
if ('function' === typeof self.options.multiple.onExist)
self.options.multiple.onExist.call(this, item);
return false;
if (self.value.length >= self.options.multiple.maxSize)
if ('function' === typeof self.options.multiple.onExceed)
self.options.multiple.onExceed.call(this, self.options.multiple.maxSize);
return false;
self.value.push(item);
self.$appender.append($tag);
var valueStr = self.value.map(function (selectedItem)
return selectedItem.id;
).join(',');
if (self.options.hidden.enable)
self.$hidden.val(valueStr);
self.$el.val('');
self.$el.data('value', valueStr);
self.$dropdown.html('').hide();
if ('function' === typeof self.options.multiple.onAppend)
self.options.multiple.onAppend.call(self, item);
,
remove: function (item)
var self = this;
self.$appender.find('[data-id="' + item.id + '"]').remove();
self.value = self.value.filter(function (selectedItem)
return selectedItem.id !== item.id;
);
var valueStr = self.value.map(function (selectedItem)
return selectedItem.id;
).join(',');
if (self.options.hidden.enable)
self.$hidden.val(valueStr);
self.$el.data('value', valueStr);
self.$dropdown.html('').hide();
if ('function' === typeof self.options.multiple.onRemove)
self.options.multiple.onRemove.call(self, item);
self.options.onRemove(item);
,
select: function (item)
var self = this;
self.value = item.text;
self.$el.val(item.text);
self.$el.data('value', item.id);
self.$dropdown.html('').hide();
if (self.options.hidden.enable)
self.$hidden.val(item.id);
self.options.onSelect(item);
;
$.fn.materialize_autocomplete = function (options)
var el = this;
var $el = $(el).eq(0);
var instance = $el.data('autocomplete');
if (instance && arguments.length)
return instance;
var autocomplete = new Autocomplete(el, options);
$el.data('autocomplete', autocomplete);
$el.dropdown();
return autocomplete;
;
));
下载这个 js 并保存在你的 js 文件夹 jquery.materialize-autocomplete.js 中,你可以覆盖 onSelect,minLength,showListOnFocus
【讨论】:
【参考方案4】:访问演示链接https://ampersandacademy.com/demo/autocomplete/
您可以使用 Devberidge 插件轻松实现自动完成功能。
使用https://github.com/devbridge/jQuery-Autocomplete获取 Devbridge 插件
<script type="text/javascript">
$(document).ready(function()
$("#country").devbridgeAutocomplete(
//lookup: countries,
serviceUrl:"getCountry.php", //tell the script where to send requests
type:'POST',
//callback just to show it's working
onSelect: function (suggestion)
// $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
,
showNoSuggestionNotice: true,
noSuggestionNotice: 'Sorry, no matching results',
);
);
这里的 getCountry.php 文件返回 JSON 数据。欲了解更多信息,请访问https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php
【讨论】:
【参考方案5】:根据 SuperDJ (https://goo.gl/0Mbrtg) 的提交,我没能成功...
代码如下:
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<input type="text" id="autocomplete" class="autocomplete highlight-matching" data-array='["value": "example","path": "","class": "","value": "example 2","path": "","class": "","value": "test","path": "","class": ""]'>
<label for="autocomplete">Autocomplete</label>
</div>
</div>
</div>
</div>
这是一个代码笔测试:
http://codepen.io/anthonyvialleton/pen/BjPjKM
需要一些帮助才能完成这项工作。
【讨论】:
我认为还没有在cdn源中;),也许很快,你需要添加源github.com/SuperDJ/materialize/blob/master/bin/materialize.cssgithub.com/SuperDJ/materialize/blob/master/bin/materialize.js 是的,这还没有被合并...所以它不能用于生产目的。我们将不得不等待所有改进和合并。 这是一个fork,不是官方项目:github.com/Dogfalo/materialize【参考方案6】:根据here。
你只需要做这个简单的事情(仅从那里的例子):
HTML:
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Autocomplete</label>
</div>
</div>
</div>
JS:
$('input.autocomplete').autocomplete(
data:
"Apple": null,
"Microsoft": null,
"Google": null
);
【讨论】:
【参考方案7】:(function (root, factory)
if(typeof module === 'object' && module.exports)
module.exports = factory(require('jquery'));
else if(typeof define === 'function' && define.amd)
define(['jquery'], factory);
else
factory(root.jQuery);
(this, function ($)
var template = function (text)
var matcher = new RegExp('<%=([\\s\\S]+?)%>|<%([\\s\\S]+?)%>|$', 'g');
var escapes =
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
;
var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match)
return '\\' + escapes[match];
;
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, interpolate, evaluate, offset)
source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
index = offset + match.length;
if (match == "<% item.value %>")
interpolate = " item.value ";
if (interpolate)
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
else if (evaluate)
source += "';\n" + evaluate + "\n__p+='";
return match;
);
source += "';\n";
source = 'with(obj||)\n' + source + '\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function()__p+=__j.call(arguments,'');;\n" +
source + 'return __p;\n';
var render;
try
render = new Function('obj', source);
catch (e)
e.source = source;
throw e;
var _template = function(data)
return render.call(this, data);
;
_template.source = 'function(obj)\n' + source + '';
return _template;
;
var Autocomplete = function (el, options)
this.options = $.extend(true, , Autocomplete.defaults, options);
this.$el = $(el);
this.$wrapper = this.$el.parent();
this.compiled = ;
this.$dropdown = null;
this.$appender = null;
this.$hidden = null;
this.resultCache = ;
this.value = '';
this.initialize();
;
Autocomplete.defaults =
cacheable: true,
limit: 10,
multiple:
enable: false,
maxSize: 4,
onExist: function (item)
Materialize.toast('Tag: ' + item.text + '(' + item.id + ') is already added!', 2000);
,
onExceed: function (maxSize, item)
Materialize.toast('Can\'t add over ' + maxSize + ' tags!', 2000);
,
onAppend: function (item)
var self = this;
self.$el.removeClass('active');
self.$el.click();
,
onRemove: function (item)
var self = this;
self.$el.removeClass('active');
self.$el.click();
,
hidden:
enable: true,
el: '',
inputName: '',
required: false
,
appender:
el: '',
tagName: 'ul',
className: 'ac-appender',
tagTemplate: '<div class="chip" data-id="<%= item.id %>" data-value="<% item.value %> data-text="<% item.text %>" "><%= item.text %>(<%= item.id %>)<i class="material-icons close">close</i></div>'
,
dropdown:
el: '',
tagName: 'ul',
className: 'ac-dropdown',
itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-value="<% item.value %>" data-text="<%= item.text %>" ><a href="javascript:void(0)"><%= item.text %></a></li>',
noItem: ''
,
handlers:
'setValue': '.ac-dropdown .ac-item',
'.ac-appender .ac-tag .close': 'remove'
,
getData: function (value, callback)
callback(value, []);
,
onSelect: function (item) ,
onRemove: function (item) alert('delete'); ,
ignoreCase: true,
throttling: true,
showListOnFocus: false,
minLength:0
;
Autocomplete.prototype =
constructor: Autocomplete,
initialize: function ()
var self = this;
var timer;
var fetching = false;
function getItemsHtml (list)
var itemsHtml = '';
if (!list.length)
return self.options.dropdown.noItem;
list.forEach(function (item, idx)
if (idx >= self.options.limit)
return false;
itemsHtml += self.compiled.item( 'item': item);
);
return itemsHtml;
function handleList (value, list)
var itemsHtml = getItemsHtml(list);
var currentValue = self.$el.val();
if (self.options.ignoreCase)
currentValue = currentValue.toUpperCase();
if (self.options.cacheable && !self.resultCache.hasOwnProperty(value))
self.resultCache[value] = list;
if (value !== currentValue)
return false;
if(itemsHtml)
self.$dropdown.html(itemsHtml);
self.$dropdown.show();
else
self.$dropdown.hide();
self.value = self.options.multiple.enable ? [] : '';
self.compiled.tag = template(self.options.appender.tagTemplate);
self.compiled.item = template(self.options.dropdown.itemTemplate);
self.render();
if (self.options.showListOnFocus)
self.$el.on('focus', function (e)
if (self.options.throttling)
clearTimeout(timer);
timer = setTimeout(function ()
self.options.getData('', handleList);
, 200);
return true;
// self.$dropdown.show();
);
self.$el.on('input', function (e)
var $t = $(this);
var value = $t.val();
if (!value)
self.$dropdown.hide();
return false;
if (self.options.ignoreCase)
value = value.toUpperCase();
if (self.resultCache.hasOwnProperty(value) && self.resultCache[value])
handleList(value, self.resultCache[value]);
return true;
if (self.options.showListOnFocus || self.options.minLength <= value.length)
if (self.options.throttling)
clearTimeout(timer);
timer = setTimeout(function ()
self.options.getData(value, handleList);
, 200);
return true;
self.options.getData(value, handleList);
);
self.$el.on('keydown', function (e)
var $t = $(this);
var keyCode = e.keyCode;
var $items, $hover;
// BACKSPACE KEY
if (keyCode == '8' && !$t.val())
if (!self.options.multiple.enable)
return true;
if (!self.value.length)
return true;
var lastItem = self.value[self.value.length - 1];
self.remove(lastItem);
return false;
// UP DOWN ARROW KEY
if (keyCode == '38' || keyCode == '40')
$items = self.$dropdown.find('[data-id]');
if (!$items.size())
return false;
$hover = $items.filter('.ac-hover');
if (!$hover.size())
$items.removeClass('ac-hover');
$items.eq(keyCode == '40' ? 0 : -1).addClass('ac-hover');
else
var index = $hover.index();
$items.removeClass('ac-hover');
$items.eq(keyCode == '40' ? (index + 1) % $items.size() : index - 1).addClass('ac-hover');
return false;
// ENTER KEY CODE
if (keyCode == '13')
$items = self.$dropdown.find('[data-id]');
if (!$items.size())
return false;
$hover = $items.filter('.ac-hover');
if (!$hover.size())
return false;
self.setValue(
id: $hover.data('id'),
text: $hover.data('text'),
value: $hover.data('value')
);
return false;
);
self.$dropdown.on('click', '[data-id]', function (e)
var $t = $(this);
var item =
id: $t.data('id'),
text: $t.data('text'),
value : $t.data('value')
;
self.setValue(item);
);
self.$appender.on('click', '[data-id] .close', function (e)
var $t = $(this);
var $li = $t.closest('[data-id');
var item =
id: $li.data('id'),
text: $li.data('text'),
value:$t.data('value')
;
self.remove(item);
);
,
render: function ()
var self = this;
if (self.options.dropdown.el)
self.$dropdown = $(self.options.dropdown.el);
else
self.$dropdown = $(document.createElement(self.options.dropdown.tagName));
self.$dropdown.insertAfter(self.$el);
self.$dropdown.addClass(self.options.dropdown.className);
if (self.options.appender.el)
self.$appender = $(self.options.appender.el);
else
self.$appender = $(document.createElement(self.options.appender.tagName));
self.$appender.insertBefore(self.$el);
if (self.options.hidden.enable)
if (self.options.hidden.el)
self.$hidden = $(self.options.hidden.el);
else
self.$hidden = $('<input type="hidden" class="validate" />');
self.$wrapper.append(self.$hidden);
if (self.options.hidden.inputName)
self.$el.attr('name', self.options.hidden.inputName);
if (self.options.hidden.required)
self.$hidden.attr('required', 'required');
self.$appender.addClass(self.options.appender.className);
,
setValue: function (item)
var self = this;
if (self.options.multiple.enable)
self.append(item);
else
self.select(item);
,
append: function (item)
var self = this;
var $tag = self.compiled.tag( 'item': item );
if (self.value.some(function (selectedItem)
return selectedItem.id === item.id;
))
if ('function' === typeof self.options.multiple.onExist)
self.options.multiple.onExist.call(this, item);
return false;
if (self.value.length >= self.options.multiple.maxSize)
if ('function' === typeof self.options.multiple.onExceed)
self.options.multiple.onExceed.call(this, self.options.multiple.maxSize);
return false;
self.value.push(item);
self.$appender.append($tag);
var valueStr = self.value.map(function (selectedItem)
return selectedItem.id;
).join(',');
if (self.options.hidden.enable)
self.$hidden.val(valueStr);
self.$el.val('');
self.$el.data('value', valueStr);
self.$dropdown.html('').hide();
if ('function' === typeof self.options.multiple.onAppend)
self.options.multiple.onAppend.call(self, item);
,
remove: function (item)
var self = this;
self.$appender.find('[data-id="' + item.id + '"]').remove();
self.value = self.value.filter(function (selectedItem)
return selectedItem.id !== item.id;
);
var valueStr = self.value.map(function (selectedItem)
return selectedItem.id;
).join(',');
if (self.options.hidden.enable)
self.$hidden.val(valueStr);
self.$el.data('value', valueStr);
self.$dropdown.html('').hide();
if ('function' === typeof self.options.multiple.onRemove)
self.options.multiple.onRemove.call(self, item);
self.options.onRemove(item);
,
select: function (item)
var self = this;
self.value = item.text;
self.$el.val(item.text);
self.$el.data('value', item.id);
self.$dropdown.html('').hide();
if (self.options.hidden.enable)
self.$hidden.val(item.id);
self.options.onSelect(item);
;
$.fn.materialize_autocomplete = function (options)
var el = this;
var $el = $(el).eq(0);
var instance = $el.data('autocomplete');
if (instance && arguments.length)
return instance;
var autocomplete = new Autocomplete(el, options);
$el.data('autocomplete', autocomplete);
$el.dropdown();
return autocomplete;
;
));
你可以使用上面的.js文件,你可以覆盖
Onselect
showListOnFocus: false,
minLength:2
根据您的要求,它将起作用。
【讨论】:
【参考方案8】:只需在 $(document).ready(function()); 中编写初始化脚本;
即
$(document).ready(function()
$('input.autocomplete').autocomplete(
data:
"Apple": null,
"Microsoft": null,
"Google": null
);
);
【讨论】:
【参考方案9】:如上所述,物化框架中添加了自动完成功能,但它仍然非常有限。我正在等待支持值(例如 ID)图标和文本的解决方案。
回复:https://github.com/Dogfalo/materialize/issues/4086
【讨论】:
这里也一样。带有 ID 的东西会是一个更好的解决方案,因为它有更多用途。以上是关于如何使用 MaterializeCss 创建自动完成表单?的主要内容,如果未能解决你的问题,请参考以下文章
如何在materializecss的单选按钮中删除字符计数器
如何使用 MaterializeCSS 在 SELECT 上调用 getSelectedValues
Materializecss & vue3:如何使用 sass @extend 为文本着色?